WebAPI 返回 200 但 SendAsync 调用显示 500

WebAPI is returning 200 but the SendAsync call shows 500

我有一个 MVC 应用程序,它在 POST 和 GET 上调用 WebAPI 异步。当 运行 本地 WebAPI 和 MVC 应用程序时,WebAPI 响应显示成功但 SendAsync 请求 returns 500。另外,Fiddler 不显示 API打电话。我怀疑这与异步请求的处理方式有关,但我不确定我遗漏了什么。

对 API 的 MVC 控制器调用:

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;
    }
}

网络API Post:

[HttpPost]
public async Task<HttpResponseMessage> Post([FromBody]Model model)
{
    var response = await SubmitNew(model);

    return Request.CreateResponse(response);
}

在 Post 中的 return 上设置断点显示有效响应,但在 MVC Controller 中的 response.Result 上显示 500。我什至尝试过 return无论响应如下,都发出 OK 请求:

return Request.CreateResponse(HttpStatusCode.OK, result);

关于客户显示 500 的原因有什么想法吗?

在你的Global.asax.cs

public class WebApiApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        // Try adding the following lines:
        var configuration = GlobalConfiguration.Configuration;
        var formatters = configuration.Formatters;
        formatters.Clear();
        formatters.Add(new JsonMediaTypeFormatter());
    }

    // A good idea to have this:
    protected void Application_Error()
    {
        Exception unhandledException = Server.GetLastError();
        // Set a breakpoint here or do something to log the exception
    }

添加到 Application_Start 的代码将确保序列化仅为 to/from JSON。虽然它可能不是您在最终代码中想要的,但作为隔离问题原因的临时措施可能会有所帮助。

添加 Application_Error 应该有助于捕获 WebAPI 层中发生的问题,例如当它序列化您从控制器方法返回的对象时。

我怀疑 SubmitNew 正在返回一些无法序列化的东西,例如无限递归引用(例如:具有相互引用的 parent/child 结构)。

我发现了问题,WebAPI 的日志记录服务在初始 POST 和 GET 调用结果之后发生超时错误。问题已解决。

我在一些代码中遇到了类似的问题 "improved" - 我看到 HttpResponseMessage 实现了 IDisposable 接口,所以决定包装 Return Request.CreateResponse 方法是一个 using 语句,引导出现 500 错误。

删除 using 语句解决了我的问题。