【问题标题】:How to accept a query and return an async task?如何接受查询并返回异步任务?
【发布时间】:2017-05-16 21:34:13
【问题描述】:

我收到以下异常:

Cannot create an EDM model as the action 'Get' on controller 'Accounts' has a return type 'System.Web.Http.IHttpActionResult' that does not implement IEnumerable<T>.

尝试查询我的端点时:

http://localhost:8267/api/accounts

正在做这项工作的 AccountsController:

    public async Task<IHttpActionResult> Get(ODataQueryOptions options)
    {
        var query = options.Request.RequestUri.PathAndQuery;
        var client = new HttpClient();
        var crmEndPoint = @"HTTPS://MYCRMORG.COM/API/DATA/V8.1/";
        HttpResponseMessage response = await client.GetAsync(crmEndPoint+query);
        object result;
        if (response.IsSuccessStatusCode)
        {
            result = await response.Content.ReadAsAsync<object>();

            return Ok(result);
        }

        return NotFound();
    }

我做错了什么?如何简单地将 PathAndQuery 添加到我的 crmEndPoint 并返回结果?

【问题讨论】:

  • OData 操作方法不应该使用IQueryable&lt;T&gt; 作为返回类型吗?

标签: c# .net asp.net-web-api2 odata dynamics-crm-2016


【解决方案1】:

OData 框架在纯 Web API 之上提供额外的响应格式/查询规则。

使用ODataQueryOptions 参数要求操作方法返回IQueryable&lt;T&gt;IEnumerable&lt;T&gt;

您的代码不需要此服务,因为它所做的只是将请求重定向到crmEndPoint。因此,您可以通过控制器的Request 属性访问请求对象,而不是使用options.Request,并完全删除参数。

代码如下:

public async Task<IHttpActionResult> Get()
{
    var query = Request.RequestUri.PathAndQuery;
    var client = new HttpClient();
    var crmEndPoint = @"HTTPS://MYCRMORG.COM/API/DATA/V8.1/";
    HttpResponseMessage response = await client.GetAsync(crmEndPoint + query);
    object result;
    if (response.IsSuccessStatusCode)
    {
        result = await response.Content.ReadAsAsync<object>();

        return Ok(result);
    }

    return NotFound();
}

【讨论】:

    猜你喜欢
    • 2013-04-16
    • 1970-01-01
    • 2019-07-13
    • 2015-01-12
    • 2014-10-01
    • 2016-08-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多