如何显示确切的错误而不是ASP.NET Web API返回UnknowError500

问题描述

当找不到公司及其公司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状态代码?

解决方法

尝试

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

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

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...