0

매우 간단한 방법의 유효성을 검사하려고하는데 'null'값이 Nullable`1 오류에 유효하지 않습니다.nullable 매개 변수에 대한 웹 API 유효성 검사가 실패합니다.

[ValidateModel] 
    public IEnumerable<SomeData> Get(bool? showExtra = null) 
    { 
     return this.MockDataManager.ShowData(showExtra); 
    } 

ValidateModel 속성은 다음과 같습니다

public override void OnActionExecuting(HttpActionContext actionContext) 
    { 
     if (actionContext != null && actionContext.ModelState.IsValid == false) 
     { 
      actionContext.Response = actionContext.Request.CreateErrorResponse(
       HttpStatusCode.BadRequest, actionContext.ModelState); 
     } 
    } 

이제 난/작동 허위 사실과 방법을 /를 호출합니다. 또한 메서드를 호출하는 경우 작동합니다 /하지만 함께 호출하는 경우/null 유효성 검사 실패 및 오류 메시지 'null'값이 Nullable에 유효하지 않습니다`1 나타납니다. 해결 방법?

답변

3

/로 전화하면/가야합니다./null에 대해 호출하는 것은 원하는 작업이 아닙니다.

여기에 무대 뒤에서 무슨 일이 일어나고 있는지의 :

/false 
OK, let's see if I can convert that into a bool. Yes, I can. 

/true 
OK, let's see if I can convert that into a bool. Yes, I can. 

/
OK, let's see if I can convert that into a bool. No, I can't, so use the default 
value specified in the method arguments. 

/null 
OK, let's see if I can convert that into a bool. No, I can't, so throw an 
exception. 
+0

나는이 방법이라고 생각 - 당신보다 더 좋은 설명! – Goran

+0

문제 없습니다. URL에'/ null' 세그먼트가 절대적으로 필요한 경우에는 다른 방법으로 메서드 인수를'bool? '에서'string'으로 변경하고 수동으로 메소드 본문의'bool? '으로 구문 분석하면됩니다 . 그 이유는 WebAPI가 'null'을 값의 부재가 아닌 값으로 취급한다는 것입니다. – danludwig

관련 문제