Man*_*101 5 c# odata asp.net-web-api
我正在努力将 OData v4 查询支持添加到继承自 ApiController 而不是 ODataController 的控制器上的方法。虽然解决方案中有一个有效的 OData 模型,但有一些端点并不真正属于该模型,但查询的功能将很有用。
我看过一些文章建议我可以只返回 IQueryable 并使用 EnableQuery。
这是我的示例代码:
public class TestController : ApiController
{
[HttpGet]
[EnableQuery]
public IQueryable<TestObject> Events()
{
var result = new[] { new TestObject { Id = "1" } }.AsQueryable();
return result;
}
}
public class TestObject
{
public string Id { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
当调用 /Test/Events 时,我得到的只是 406 Not Acceptable,这是我在处理 OData 时遇到的很多情况,这通常意味着我返回了 OData 框架不喜欢的东西。我从来没有能够从框架中获得更多信息(我认为这是一个重大失败)来解释为什么它不喜欢它,并且过去只能通过反复试验来解决它们。
有没有人让这个设置工作,如果是的话如何?
Or any suggestions on debugging the 406 response?
EDIT:
OK so it turned out the culprit was so code in the start up that was registering a custom ODataMediaTypeFormatter and in the process was clearing all other formatters.
After removing the offending code it worked.
Really really wish WebApi would record somewhere what caused the 406 error when it spits one out.
小智 0
您可以手动应用“查询”魔法,无需 [EnableQuery]。
需要进一步操纵并返回。请记住,返回类型不需要是 IQueryable<yourEntity>,甚至不需要基于“yourEntity”。
下面是一个类似的实现,它针对 ODataController 方法执行此操作(作为基本 ODataQueryOptions 是免费提供的):
public IEnumerable<Aggregate> GetOrders(ODataQueryOptions<ReportingOrder> opts, [FromUri(Name="$groupby")]string groupby, [FromUri(Name="$aggregates")]string aggregates = null)
{
var url = opts.Request.RequestUri.AbsoluteUri;
int? top = null;
if (opts.Top != null)
{
top = int.Parse(opts.Top.RawValue);
var topStr = string.Format("$top={0}", top.Value);
url = url.Replace(topStr, "");
var req = new HttpRequestMessage(HttpMethod.Get, url);
opts = new ODataQueryOptions<ReportingOrder>(opts.Context, req);
}
var query = opts.ApplyTo(db.ReportingOrders.AsQueryable()) as IQueryable<ReportingOrder>;
var results = query.GroupBy(groupby, aggregates, top);
return results;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3607 次 |
| 最近记录: |