【问题标题】:How to show exact error instead of ASP.NET Web API return UnknowError(500)如何显示确切的错误而不是 ASP.NET Web API 返回 UnknowError(500)
【发布时间】:2020-12-07 14:11:40
【问题描述】:

当找不到带有公司 ID 的公司时,我想返回 404 状态码。但是 Web API 总是返回;

  "error": {
    "message": "An error has occurred. Please, try it later.",
    "issuedAt": "2020-08-18T08:06:19.4650733Z",
    "code": "UnknownError",
    "statusCode": 500
  }
}

这是我的 CustomerProvider 代码;

public class CustomerProvider: ICustomerProvider
    {
        public CustomerProvider GetCustomerDetails()
        {
            //.....
            //.....
            
                if (customerDetails == null)
                {
                    var resp = new HttpResponseMessage(HttpStatusCode.NotFound)
                    {
                        Content = new StringContent(string.Format("No customer with ID = {0}", customerId)),
                        ReasonPhrase = "Company ID Not Found"
                    };
                    throw new HttpResponseException(resp);
                }
            
                return customerDetails;
        }
    }

如何返回 404 状态码?

【问题讨论】:

    标签: asp.net exception asp.net-web-api2 http-status-code-404


    【解决方案1】:

    试试

    HttpResponseMessage err_response = (HttpResponseMessage)Request.CreateErrorResponse(HttpStatusCode.NotFound, "Your Message");
    return err_response;
    

    我不建议因为它不是(404)它是“服务器错误(500)”

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-04
      • 2021-06-01
      • 2016-03-16
      • 2010-11-04
      • 2017-10-28
      • 2021-09-24
      • 2020-07-06
      • 2021-08-29
      相关资源
      最近更新 更多