问题描述
从 .net Framework 迁移到 .net Standard/Core 时我遇到了 HttpError 类.除了只是临时解决方案的兼容性垫片之外,我在 .net 核心/标准中找不到任何等效项.
While migrating form .net Framework to .net Standard/CoreI came across the HttpError class.I can't find any equivalent in .net core/standard except of the Compatability Shim which is just a temporary solution.
不知道有没有官方的替代品?也许 API 已更改,并且可以使用新的最佳实践来代替 HttpError.
Do you know if there is an official replacement for it? Maybe the API has changed and there is a new best practice to use instead of HttpError.
谢谢!
推荐答案
HttpError 对象提供了一种在响应正文中返回错误信息的一致方式.在 asp.net Core Web API 中,您可以定义一个基本的 ApiResponse 类,如:
The HttpError object provides a consistent way to return error information in the response body. In asp.net Core Web API, you can define a base ApiResponse class like :
public class ApiResponse
{
public int StatusCode { get; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public string Message { get; }
public ApiResponse(int statusCode, string message = null)
{
StatusCode = statusCode;
Message = message ?? GetDefaultMessageForStatusCode(statusCode);
}
private static string GetDefaultMessageForStatusCode(int statusCode)
{
switch (statusCode)
{
...
case 404:
return "Resource not found";
case 500:
return "An unhandled error occurred";
default:
return null;
}
}
}
你也可以派生这个类来定义更具体的预定义错误类型,请参考this 和 这篇文章了解更多详情和代码示例.
You can also derive this class to define more specific predefined error types, please refer to this and this article for more details and code sample .
从 2.1 版开始,它增加了对 RFC 7807 – HTTP API 的问题详细信息的支持 作为从 HTTP API 返回机器可读错误响应的标准化格式:
From version 2.1 ,it added support for RFC 7807 – Problem Details for HTTP APIs as a standardized format for returning machine readable error responses from HTTP APIs:
参考:https://blogs.msdn.microsoft.com/webdev/2018/02/27/asp-net-core-2-1-web-apis/
这篇关于.Net 标准/核心版本的 system.web.http.HttpError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!