5

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

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

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

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

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

提前致谢!

4

2 回答 2

4

找到了上面的实现方式 -

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

于 2018-03-07T08:12:29.483 回答
2

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

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

启动.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"
}
于 2020-04-16T11:21:34.450 回答