我想通过它的名字找到它来返回这个对象:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public string Category { get; set; }
}
控制器方法是:
[HttpGet]
[ODataRoute("Products/ProductService.GetByName(Name={name})")]
public IHttpActionResult GetByName([FromODataUri]string name)
{
Product product = _db.Products.Where(x => x.Name.Equals(name, StringComparison.OrdinalIgnoreCase)).SingleOrDefault();
if (product == null)
{
return NotFound();
}
return Ok(product);
}
WebApiConfig.Register()方法是:
public static void Register(HttpConfiguration config)
{
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<Product>("Products");
builder.Namespace = "ProductService";
builder.EntityType<Product>().Collection.Function("GetByName").Returns<Product>().Parameter<string>("Name");
config.MapODataServiceRoute(routeName: "ODataRoute", routePrefix: null, model: builder.GetEdmModel());
}
通过调用http:// http:// localhost:52542 / Products(1),我确实得到ID为1的产品:
{
"@odata.context":"http://localhost:52542/$metadata#Products/$entity","Id":1,"Name":"Yo-yo","Price":4.95,"Category":"Toy"
}
但是当我调用http:// http:// localhost:52542 / Products / ProductService.GetByName(Name =’yo-yo’)时我可以调试到控制器函数并返回结果但是我得到了一个浏览器中显示错误已发生错误..消息是’ObjectContent 1’类型无法序列化内容类型’application / json的响应正文; odata.metadata =最小”.内部异常是无法从OData路径中找到相关实体集或单例.需要相关的实体集或单例来序列化有效负载.
这有什么不对?
解决方法:
您的功能配置有一些问题.
您应该按如下方式调用以定义返回:
builder.EntityType<Product>().Collection.Function("GetByName").ReturnsFromEntitySet<Product>("Products").Parameter<string>("Name");
然后它可以工作.谢谢.