C# 异步方法的Web api返回值
我对C# 异步方法的Web api返回值,c#,asynchronous,asp.net-web-api,async-await,C#,Asynchronous,Asp.net Web Api,Async Await,我对HttpResponseMessage和Task有点困惑 如果我使用HttpClient方法PostAsync()发布数据,我需要将Task作为返回值,而不是HttpResponseMessage 如果我使用Request.CreateResponse(HttpStatusCode.probled,myError.ToString()) 然后我只得到响应消息对象,而不是任务对象 所以我这里的问题是,如何为web api方法的异步调用创建合适的返回? (因此,我的理解是否正确,如果正确,如何在
HttpResponseMessage
和Task
有点困惑
如果我使用HttpClient
方法PostAsync()
发布数据,我需要将Task
作为返回值,而不是HttpResponseMessage
如果我使用Request.CreateResponse(HttpStatusCode.probled,myError.ToString())代码>
然后我只得到响应消息对象,而不是任务
对象
所以我这里的问题是,如何为web api方法的异步调用创建合适的返回?
(因此,我的理解是否正确,如果正确,如何在任务对象中最好地转换消息对象)
原代码:
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)
公共任务设备登录(MyDevice)
WebAPI2有这些现在推荐使用的抽象类。您仍然可以使用HttpResponseMessage
(在我看来,初学者更容易理解),但WebAPI2建议使用IHttpActionResult
至于返回类型,就像你以前做的那样<代码>任务
以这种方式自动工作
您可能还需要检查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()));
}
}
公共异步任务设备登录(MyDevice)
{
EnummyError myError=EnummyError.None;
//验证设备。
myError=此。验证(设备);
//也许Authenticate有这样一个异步方法。
//myError=等待此消息。AuthenticateTasync(设备);
if(myError!=EnummyError.None)
{
返回ResponseMessage(Request.CreateResponse(Request.CreateResponse(HttpStatusCode.Forbidded,myError.ToString());
}
}
ResponseMessage()
方法在水下创建一个ResponseMessageResult
。该类派生自IHttpActionResult
,并接受HttpResponseMessage
作为构造函数中的参数(由请求.CreateResponse()
生成).我不是在听你的问题。你有一些代码可以解释这个问题吗?你自己并没有对任务做任何事情,框架会处理它,你只返回你要返回的类型。你是在使用Web Api版本1还是2?@Baksteen visual Studio 2017,所以用示例代码在一秒钟内更新v2会有一个问题吗Authenticate需要一个异步方法吗?hmmm编译器说ResponseMessage不能以这种方式转换为Taskworks。但问题仍然是:我必须在内部使用Wait吗?还是“你最好这样做”,…?啊!我的错。我忘了在方法声明中添加async
。我已经更新了我的答案。至于身份验证,没有。但是如果你没有为异步方法调用使用任何wait
操作符,那么就没有必要使这个方法异步,因为它只会同步运行。你必须仔细考虑并可能重新设计它在那里签名/提出一个新问题,但当前问题已解决,因此thnx。