c# - 异步方法的 Web api 返回值

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

我对 HttpResponseMessage 有点困惑和 Task<HttpResponseMessage> .

如果我使用 HttpClient方法 PostAsync()要发布数据,我需要为 Web 服务方法提供 Task<HttpResponseMessage>而不是 HttpResponseMessage据我了解,作为返回值。

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

所以我的问题是如何为异步调用 Web API 方法创建 Fitting 返回值? (因此我的理解是否正确,如果正确,如何最好地将消息对象转换为 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 2 有这些抽象类,现在推荐使用。您仍然可以使用 HttpResponseMessage (在我看来,对于初学者来说更容易理解),但 Web Api 2 建议使用 IHttpActionResult .

至于返回类型,按照你之前做的就好了。 Task<T>以这种方式自动工作。

您可能还想检查是否 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() 生成)。

关于c# - 异步方法的 Web api 返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47589417/

相关文章:

c# - 为什么在控制台应用程序中使用 async/await 时需要 AsyncContext?

c# - ASP .NET WebAPI 无法访问路由

android - Web API 服务器 Controller 未获取参数

c# - SQL 数据读取器 SQL Server 核心实现

c# - 控制台 C# 乌尔都语书写不可读

c# - 一行if语句,如何转换这个if-else-statement

javascript - 异步代码执行解释

c# - C# 中的西里尔编码

javascript - Simon游戏javascript,如何使用animation()和delay() JQUERY同步按钮的灯光而不互相踩踏?

javascript - Angular.js $resource 与 ASP.Net webapi?