내 요청에 대한 사용자 지정 메시지가 필요합니다.
현재 나는 우편 배달부의 요청 json 아래를 전달하고 있습니다.
{
"countryid": "14sdsads02"
}
하지만 내 모델은
public class model{
public int countryid {get;set;}
}
우편 배달원의 요청을 통과하면 오류가 발생합니다.
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "|21793cf-495c68ddbc92ab35.",
"errors": {
"$.countryid": [
"The JSON value could not be converted to System.Int32. Path: $.countryid | LineNumber: 1 | BytePositionInLine: 29."
]
}
}
하지만이 대신 웹 API에 사용자 지정 오류가 필요합니다. 이것을 어떻게 달성 할 수 있습니까?
400의 경우 사용자 지정 응답을 정의하려면 다음을 수행 할 수 있습니다.
모델 바인딩 오류를 포착하려면 ApiBehaviorOptions
의 InvalidModelStateResponseFactory
( 1 )에 대한 처리기를 연결해야합니다 .
필수 델리게이트는 매우 일반적입니다 : Func<ActionContext, IActionResult>
. 따라서 먼저이를위한 인터페이스를 생성 해 보겠습니다.
public interface IModelBindingErrorHandler
{
IActionResult HandleInvalidModelState(ActionContext context);
}
다음은 간단한 핸들러 구현입니다.
public class ModelBindingErrorHandler : IModelBindingErrorHandler
{
private ICorrelationContextAccessor correlationContextAccessor;
private ILogger logger;
public ModelBindingErrorHandler(ICorrelationContextAccessor correlationContextAccessor, ILogger logger)
{
this.correlationContextAccessor = correlationContextAccessor;
this.logger = logger;
}
public IActionResult HandleInvalidModelState(ActionContext context)
{
string correlationId = correlationContextAccessor.CorrelationContext?.CorrelationId;
var modelErrors = context.ModelState
.Where(stateEntry => stateEntry.Value.Errors.Any())
.Select(stateEntry => new InvalidData
{
FieldName = stateEntry.Key,
Errors = stateEntry.Value.Errors.Select(error => error.ErrorMessage).ToArray()
});
logger.LogError("The request contained malformed input.", modelErrors);
var responseBody = new GlobalErrorModel
{
ErrorMessage = "Sorry, the request contains invalid data. Please revise.",
ErrorTracingId = correlationId
};
return new BadRequestObjectResult(responseBody);
}
}
도우미 클래스
public class GlobalErrorModel
{
public string ErrorMessage { get; set; }
public string ErrorTracingId { get; set; }
}
public class InvalidData
{
public string FieldName { get; set; }
public string[] Errors { get; set; }
public override string ToString() => $"{FieldName}: {string.Join("; ", Errors)}";
}
public static class ModelBindingErrorHandlerRegister
{
/// <summary>
/// This method should be called after <b>AddControllers();</b> call.
/// </summary>
public static IServiceCollection AddModelBinderErrorHandler(this IServiceCollection services)
{
return AddModelBinderErrorHandler<ModelBindingErrorHandler>(services);
}
/// <summary>
/// This method can be used to register a custom Model binder's error handler.
/// </summary>
/// <typeparam name="TImpl">A custom implementation of <see cref="IModelBindingErrorHandler"/></typeparam>
public static IServiceCollection AddModelBinderErrorHandler<TImpl>(this IServiceCollection services)
where TImpl : class, IModelBindingErrorHandler
{
services.AddSingleton<IModelBindingErrorHandler, TImpl>();
var serviceProvider = services.BuildServiceProvider();
var handler = serviceProvider.GetService<IModelBindingErrorHandler>();
services.PostConfigure((ApiBehaviorOptions options) =>
options.InvalidModelStateResponseFactory = handler.HandleInvalidModelState);
return services;
}
}
public partial class Startup
{
private readonly IConfiguration Configuration;
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers()
.AddNewtonsoftJson();
//Omited for brevity
services.AddModelBinderErrorHandler();
}
//Omited for brevity
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다