我有一个在 POST 和 GET 上调用 WebAPI 异步的 MVC 应用程序。在本地运行 WebAPI 和 MVC 应用程序时,WebAPI 响应显示成功,但 SendAsync 请求返回 500。此外,Fiddler 不显示 API 调用。我怀疑它与异步请求的处理方式有关,但我不确定我错过了什么。
MVC 控制器对 API 的调用:
public Model UploadFile(Model formCollection)
{
var documentModel = formCollection.ToString();
var client = new HttpClient();
var uri = new Uri(BaseUri + "document/");
var content = new StringContent(documentModel);
var request = new HttpRequestMessage(HttpMethod.Post, uri) {Content = content};
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var response = client.SendAsync(request);
response.Wait();
try
{
var returned = response.Result;
if (returned.StatusCode != HttpStatusCode.OK)
{
throw new Exception(returned.RequestMessage.ToString());
}
var model = JsonConvert.DeserializeObject<Model> (returned.Content.ReadAsStringAsync().Result);
model.FileContents = "";
return model;
}
catch(Exception e)
{
var error = new Exception("Service failure - ", e);
throw error;
}
}
WebAPI 帖子:
[HttpPost]
public async Task<HttpResponseMessage> Post([FromBody]Model model)
{
var response = await SubmitNew(model);
return Request.CreateResponse(response);
}
在 Post 中设置返回断点显示有效响应,但在 MVC 控制器中的 response.Result 上显示 500。我什至尝试返回 OK 请求,无论响应如下:
return Request.CreateResponse(HttpStatusCode.OK, result);
关于为什么客户显示 500 的任何想法?