我想通过它的名字找到它来返回这个对象:
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public string Category { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
控制器方法是:
[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);
}
Run Code Online (Sandbox Code Playgroud)
和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());
}
Run Code Online (Sandbox Code Playgroud)
通过调用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"
}
Run Code Online (Sandbox Code Playgroud)
但是当我正在调用时,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..
这有什么不对?
您的功能配置有一些问题.您应该按如下方式调用以定义返回:
builder.EntityType<Product>().Collection.Function("GetByName").ReturnsFromEntitySet<Product>("Products").Parameter<string>("Name");
Run Code Online (Sandbox Code Playgroud)
然后它可以工作.谢谢.