【发布时间】:2021-03-14 18:49:31
【问题描述】:
我有一个 ASP.NET MVC 应用程序,它正在调用 WEB API REST 服务方法。
如果操作成功与否,我正在使用自定义 MyBoolResult 对象返回。这是一个具有一些构造函数和属性的类。
现在我正在尝试在 DoWork 方法中将 Task 转换为 MyBoolResult。我怎样才能做到这一点?
下面的代码sn-p:
public MyBoolResult DoWork()
{
string requestUri = "api/MyController/CreateFile";
CustomObject myParams = new CustomObject();
// Below line does not work. How can I convert the returned object into MyBoolResult?
MyBoolResult myBoolObject = this.CreateFile(requestUri, myParams);
return myBoolObject;
}
public async Task<MyBoolResult> CreateFile(string requestUri)
{
// Here some stuff and initializations
// To simplify I am not putting here all the code previous to PostAsync
HttpResponseMessage res = await client.PostAsync(requestUri, httpContent);
if (res.IsSuccessStatusCode)
{
var webApiResp = res.Content.ReadAsStringAsync().Result;
result = Newtonsoft.Json.JsonConvert.DeserializeObject<MyBoolResult>(webApiResp);
}
else
{
result = MyBoolResult.ToErrorResult(String.Format("An error occurred! HTTP error code {0}", res.StatusCode));
}
return result;
}
【问题讨论】:
标签: c# asp.net-mvc asp.net-web-api async-await asp.net-web-api2