【问题标题】:Web api return values for async methods异步方法的 Web api 返回值
【发布时间】:2018-05-15 07:47:15
【问题描述】:

我对@9​​87654321@ 和Task<HttpResponseMessage> 有点困惑。

如果我使用HttpClient 方法PostAsync() 发布数据,我需要将Task<HttpResponseMessage> 而不是HttpResponseMessage 作为返回值,据我所知。

如果我使用Request.CreateResponse(HttpStatusCode.Forbidden, myError.ToString()); 那么我只得到响应消息对象而不是Task 对象。

所以我的问题是如何为对 web api 方法的异步调用创建拟合返回? (因此我的理解是正确的,如果是这样,如何最好地将消息对象转换为 Task<HttpResponseMessage> 对象)

原代码:

public HttpResponseMessage DeviceLogin(MyDevice device)
{
    EnummyError myError = EnummyError.None;

    // Authenticate Device.
    myError = this.Authenticate(device);

    if (myError != EnummyError.None)
    {
        return Request.CreateResponse(HttpStatusCode.Forbidden, myError.ToString());
    }
}

更新的方法头:

public Task<HttpResponseMessage> DeviceLogin(MyDevice device)

【问题讨论】:

  • 我没有关注你的问题。你有一些代码可以解释这个问题吗?你自己并没有真正对任务做任何事情,框架会处理它,你只是返回你无论如何都会返回的类型。
  • 您使用的是 Web Api 版本 1 还是 2?
  • @Baksteen Visual Studio 2017 所以 v2 会在一秒钟内更新示例代码

标签: c# asynchronous asp.net-web-api async-await


【解决方案1】:

Web Api 2 具有这些现在推荐使用的抽象类。你仍然可以使用HttpResponseMessage(我认为初学者更容易理解),但Web Api 2 建议使用IHttpActionResult

至于返回类型,只是做了你之前做的。 Task&lt;T&gt; 以这种方式自动工作。

您可能还想检查this.Authenticate() 是否有async 变体。

public async Task<IHttpActionResult> DeviceLogin(MyDevice device)
{
    EnummyError myError = EnummyError.None;

    // Authenticate Device.
    myError = this.Authenticate(device);

    // Perhaps Authenticate has an async method like this.
    // myError = await this.AuthenticateAsync(device);


    if (myError != EnummyError.None)
    {
        return ResponseMessage(Request.CreateResponse(Request.CreateResponse(HttpStatusCode.Forbidden, myError.ToString()));
    }
}

ResponseMessage() 方法在水下创建一个ResponseMessageResult。该类派生自IHttpActionResult,并接受HttpResponseMessage 作为构造函数中的参数(由Request.CreateResponse() 创建)。

【讨论】:

  • 身份验证是否需要异步方法?
  • hmmm 编译器说 ResponseMessage 不能转换成 Task
  • 就是这样工作的。问题仍然存在:我必须在里面使用 await 吗?还是“你最好应该”,...?
  • 啊!我的错。我忘了在方法声明中添加async。我已经更新了我的答案。至于身份验证,不,它没有。但是如果你不使用任何await 操作符进行异步方法调用,那么让这个方法异步是没有用的,因为它只会同步运行
  • 将不得不重新考虑并可能在那里重新设计/提出一个新问题,但是这个当前的问题已经解决了。
猜你喜欢
  • 1970-01-01
  • 2012-12-20
  • 2016-08-30
  • 2012-08-08
  • 2011-09-06
  • 2015-03-30
  • 1970-01-01
  • 2012-10-27
  • 1970-01-01
相关资源
最近更新 更多