Web api dotnet 核心中 Api 版本控制错误的自定义错误响应

Customized error responses for ApiVersioning errors in webapi dotnet core

我正在为 Webapi 服务中的所有错误创建一个包库。该库将用于为 BadRequest、BadArgument、ApiVersionsing 等相关错误提供自定义响应。我需要帮助自定义与 Apiversion 相关的错误 - ApiVersionUnspecified、UnsupportedApiVersion、InvalidApiVersion、AmbiguousApiVersion。我已按照这篇文章为我的项目添加 api-版本控制 - https://www.hanselman.com/blog/ASPNETCoreRESTfulWebAPIVersioningMadeEasy.aspx

我已经检查了上述包的 github wiki,发现“根据所需的行为,您可以扩展 DefaultErrorResponseProvider 或者您可以从 stratch 实现您自己的 IErrorResponseProvider。

要设置备用错误响应行为,请将默认提供程序替换为您自己的:

options => options.ErrorResponses = new MyErrorResponseProvider();

但是;我不太明白如何在 MyErrorResponseProvider class 中自定义默认错误响应。有人可以给我提供任何示例,以便我开始使用吗?

提前致谢!

找到上面的实现方式为 -

class MyErrorResponseProvider : DefaultErrorResponseProvider
{
// note: in Web API the response type is HttpResponseMessage
public override IActionResult CreateResponse( ErrorResponseContext context )
{
       switch ( context.ErrorCode )
       {
           case "UnsupportedApiVersion":
               context = new ErrorResponseContext(
                   context.Request,
                   context.StatusCode,
                   context.ErrorCode,
                   "My custom error message.",
                   context.MessageDetail );
               break;
       }

       return base.CreateResponse( context );
}
}

感谢github问题@ - https://github.com/Microsoft/aspnet-api-versioning/issues/233

答案仅自定义 ASP.NET API 版本控制返回的错误消息。

要自定义整个响应,您可以通过返回 ObjectResult 来实现它。

Startup.cs

// Add API Versioning to the service container to your project
        services.AddApiVersioning(config =>
        {
            // Advertise the API versions supported for the particular endpoint
            config.ReportApiVersions = true;
            config.ErrorResponses = new ApiVersioningErrorResponseProvider();//Send standard error response when API version error.
        });

ApiVersioningErrorResponseProvider.cs

using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Versioning;

public class ApiVersioningErrorResponseProvider : DefaultErrorResponseProvider
{
    public override IActionResult CreateResponse(ErrorResponseContext context)
    {
       //You can initialize your own class here. Below is just a sample.
        var errorResponse = new
        {
            ResponseCode = 101,
            ResponseMessages = "Something went wrong while selecting the api version",
            HelpLink = "https://github.com/microsoft/aspnet-api-versioning/wiki/Error-Response-Provider"
        };
        var response = new ObjectResult(errorResponse);
        response.StatusCode = (int)HttpStatusCode.BadRequest;

        return response;
    }
}

产生以下输出:

{
"ResponseCode": 101,
"ResponseMessages": "Something went wrong while selecting the api version",
"HelpLink": "https://github.com/microsoft/aspnet-api-versioning/wiki/Error-Response-Provider"
}