问题描述
从.net Framework迁移到.net Standard/Core时我遇到了HttpError类.除了Compatability Shim只是临时解决方案之外,我在.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;
}
}
}
您还可以派生此类来定义更特定的预定义错误类型,请参考此和这篇文章以获取更多详细信息和代码示例.
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!