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