【问题标题】:WebAPI is returning 200 but the SendAsync call shows 500WebAPI 返回 200 但 SendAsync 调用显示 500
【发布时间】:2017-05-09 07:45:25
【问题描述】:

我有一个在 POST 和 GET 上调用 WebAPI 异步的 MVC 应用程序。在本地运行 WebAPI 和 MVC 应用程序时,WebAPI 响应显示成功,但 SendAsync 请求返回 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;
    }
}

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 的任何想法?

【问题讨论】:

  • 然后包装 var response = client.SendAsync(request);使用 try-catch 块并查看异常
  • 错误 500 表示您的 WebAPI 配置错误。您是否有更简单的 WebAPI 获取方法进行测试以帮助您确认 API 是否正常工作?
  • 使用 POSTMAN/Advanced rest 客户端进行此调用,您将能够在响应正文中看到错误详细信息
  • 如上所述使用邮递员,或者不要使用 RequestMessage 抛出异常(不包含实际响应),尝试读取响应 .Content.ReadAsStringAsync() 并检查它。
  • 我发现了问题,在初始 POST 和 GET 调用结果之后,WebAPI 的日志记录服务出现超时错误。问题已解决。

标签: c# asp.net-mvc asp.net-mvc-4 asp.net-web-api sendasync


【解决方案1】:

我“改进”的一些代码也有类似的问题 - 我看到 HttpResponseMessage 实现了 IDisposable 接口,因此决定包装 Return Request.CreateResponse 方法是一个 using 语句,导致 500 错误。

删除 using 语句为我解决了这个问题。

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      在您的 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 的代码将确保序列化仅针对/来自 JSON。虽然它可能不是您在最终代码中想要的,但作为隔离问题原因的临时措施可能会有所帮助。

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

      我怀疑SubmitNew 正在返回无法序列化的内容,例如无限递归引用(例如:具有相互引用的父/子结构)。

      【讨论】:

        猜你喜欢
        • 2013-12-26
        • 1970-01-01
        • 1970-01-01
        • 2020-06-23
        • 2014-04-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-11
        相关资源
        最近更新 更多