我对 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/