webapi dotnet核心中ApiVersioning错误的自定义错误响应

时间:2018-03-06 06:15:08

标签: c# error-handling .net-core custom-error-handling api-versioning

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

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

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

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

然而;我不知道如何在MyErrorResponseProvider类中自定义默认错误响应。有人可以请我提供任何示例,以便我可以开始这个吗?

提前致谢!

2 个答案:

答案 0 :(得分:2)

找到上面的实现方式 -

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

答案 1 :(得分:1)

答案仅自定义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"
}