웹 API .net 코어 3.1에서 문자열 대신 int를 전달할 때 400 잘못된 요청

부드러운 가치

내 요청에 대한 사용자 지정 메시지가 필요합니다.

현재 나는 우편 배달부의 요청 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의 경우 사용자 지정 응답을 정의하려면 다음을 수행 할 수 있습니다.

핸들러

모델 바인딩 오류를 포착하려면 ApiBehaviorOptionsInvalidModelStateResponseFactory( 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] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

400-Python에서 pushalot API를 사용할 때 잘못된 요청

분류에서Dev

400-Python에서 pushalot API를 사용할 때 잘못된 요청

분류에서Dev

Spotify API에서 액세스 토큰에 대한 코드를 교환 할 때 왜 계속 400 잘못된 요청 오류가 발생합니까?

분류에서Dev

Google Gmail API에 토큰 요청을 할 때 잘못된 요청 400

분류에서Dev

Google Gmail API에 토큰 요청을 할 때 잘못된 요청 400

분류에서Dev

React에서 Harvest API 인증을 시도 할 때 잘못된 요청 (400)

분류에서Dev

Kendo Grid에서 내 서비스를 호출 할 때 400 잘못된 요청

분류에서Dev

Saber API에 연결을 시도 할 때 오류 (400) 잘못된 요청

분류에서Dev

PUT 호출에 대한 400 잘못된 요청 Asp Net Web Api 2.2

분류에서Dev

IP 주소를 사용하여 호스트에 액세스 할 때 웹 API 2 잘못된 요청

분류에서Dev

HTTP 400 : Azure Blob에 추가 할 때 잘못된 요청

분류에서Dev

AWS S3-미리 서명 된 URL을 통해 파일을 PUTting 할 때 400 잘못된 요청

분류에서Dev

400 클라이언트에서 서버로 JSON 문자열을 보낼 때 잘못된 요청 예외

분류에서Dev

Open Weather API (위치 정보)를 가져올 때 오류 400 잘못된 요청

분류에서Dev

Postman에서 Rest API를 호출 할 수 있으며 Java에서 400 개의 잘못된 요청이 표시됨

분류에서Dev

S3 GET 요청시 400 잘못된 요청 수신

분류에서Dev

asp.net 웹 API에서 FromBody를 사용할 때 문자열 값이 비어 있음

분류에서Dev

Spring RestTemplate으로 byte []를 SpringMVC rest endpoint에 업로드 할 때 400 잘못된 요청

분류에서Dev

HTTP 상태 400 – 데이터베이스에 날짜를 저장하려고 할 때 잘못된 요청

분류에서Dev

어떻게 자바에서 HTTP 응답 코드 (400) 오류를 수정하려면? 어떤 잘못된 요청 구문 또는 잘못된 요청 메시지 프레이밍이 있습니까?

분류에서Dev

axios 오류에서 헤더 전달 : 400 잘못된 요청

분류에서Dev

http : // localhost : 3000 / api / stuff에 대한 HTTP 실패 응답 : 400 잘못된 요청

분류에서Dev

Facebook에서 Socialite를 사용할 때 잘못된 요청

분류에서Dev

Post에서 이미지를 요청할 때 잘못된 호출

분류에서Dev

400 잘못된 요청을 수신하는 POST를 전송하여 JQuery $ .ajax

분류에서Dev

asp.net의 httprequest에서 웹 API에 대한 get 요청 전달

분류에서Dev

"http : // localhost : 61961 / Token"을 사용하여 웹 API에 로그인하려고합니다. 400 잘못된 요청 오류 수신

분류에서Dev

Spark에서 잘못된 시간대 문자열을 전달할 때 from_utc_timstamp가 오류를 발생시키지 않는 이유는 무엇입니까?

분류에서Dev

Spring 컨트롤러에 JSON 전달시 400 (잘못된 요청)

Related 관련 기사

  1. 1

    400-Python에서 pushalot API를 사용할 때 잘못된 요청

  2. 2

    400-Python에서 pushalot API를 사용할 때 잘못된 요청

  3. 3

    Spotify API에서 액세스 토큰에 대한 코드를 교환 할 때 왜 계속 400 잘못된 요청 오류가 발생합니까?

  4. 4

    Google Gmail API에 토큰 요청을 할 때 잘못된 요청 400

  5. 5

    Google Gmail API에 토큰 요청을 할 때 잘못된 요청 400

  6. 6

    React에서 Harvest API 인증을 시도 할 때 잘못된 요청 (400)

  7. 7

    Kendo Grid에서 내 서비스를 호출 할 때 400 잘못된 요청

  8. 8

    Saber API에 연결을 시도 할 때 오류 (400) 잘못된 요청

  9. 9

    PUT 호출에 대한 400 잘못된 요청 Asp Net Web Api 2.2

  10. 10

    IP 주소를 사용하여 호스트에 액세스 할 때 웹 API 2 잘못된 요청

  11. 11

    HTTP 400 : Azure Blob에 추가 할 때 잘못된 요청

  12. 12

    AWS S3-미리 서명 된 URL을 통해 파일을 PUTting 할 때 400 잘못된 요청

  13. 13

    400 클라이언트에서 서버로 JSON 문자열을 보낼 때 잘못된 요청 예외

  14. 14

    Open Weather API (위치 정보)를 가져올 때 오류 400 잘못된 요청

  15. 15

    Postman에서 Rest API를 호출 할 수 있으며 Java에서 400 개의 잘못된 요청이 표시됨

  16. 16

    S3 GET 요청시 400 잘못된 요청 수신

  17. 17

    asp.net 웹 API에서 FromBody를 사용할 때 문자열 값이 비어 있음

  18. 18

    Spring RestTemplate으로 byte []를 SpringMVC rest endpoint에 업로드 할 때 400 잘못된 요청

  19. 19

    HTTP 상태 400 – 데이터베이스에 날짜를 저장하려고 할 때 잘못된 요청

  20. 20

    어떻게 자바에서 HTTP 응답 코드 (400) 오류를 수정하려면? 어떤 잘못된 요청 구문 또는 잘못된 요청 메시지 프레이밍이 있습니까?

  21. 21

    axios 오류에서 헤더 전달 : 400 잘못된 요청

  22. 22

    http : // localhost : 3000 / api / stuff에 대한 HTTP 실패 응답 : 400 잘못된 요청

  23. 23

    Facebook에서 Socialite를 사용할 때 잘못된 요청

  24. 24

    Post에서 이미지를 요청할 때 잘못된 호출

  25. 25

    400 잘못된 요청을 수신하는 POST를 전송하여 JQuery $ .ajax

  26. 26

    asp.net의 httprequest에서 웹 API에 대한 get 요청 전달

  27. 27

    "http : // localhost : 61961 / Token"을 사용하여 웹 API에 로그인하려고합니다. 400 잘못된 요청 오류 수신

  28. 28

    Spark에서 잘못된 시간대 문자열을 전달할 때 from_utc_timstamp가 오류를 발생시키지 않는 이유는 무엇입니까?

  29. 29

    Spring 컨트롤러에 JSON 전달시 400 (잘못된 요청)

뜨겁다태그

보관