我希望通过它的名字来找回它:
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')
时,我可以调试控制器函数并返回结果但是我在浏览器中收到错误An error has occurred.
。消息为The 'ObjectContent 1' type failed to serialize the response body for content type 'application/json; odata.metadata=minimal'.
,内部异常为The related entity set or singleton cannot be found from the OData path. The related entity set or singleton is required to serialize the payload.
。
这里有什么问题?
答案 0 :(得分:6)
您的功能配置存在一些问题。 您应该按如下方式调用以定义返回:
builder.EntityType<Product>().Collection.Function("GetByName").ReturnsFromEntitySet<Product>("Products").Parameter<string>("Name");
然后它可以工作。感谢。