모델 클래스의 속성에서 사용할 사용자 지정 JsonConverter를 구축하고 있습니다. 모델은 Web API 컨트롤러에서 입력 매개 변수로 사용됩니다. 내 JsonConverter FormatException
에서 입력이 마음에 들지 않으면 던지고 있습니다.
내 모델의 일부는 다음과 같습니다.
public class PropertyVM
{
public string PropertyId { get; set; }
[JsonConverter( typeof(BoolConverter) )]
public bool IsIncludedInSearch { get; set; }
}
내 컨트롤러 작업은 다음과 같습니다.
[HttpPost, Route("{propertyId}")]
public IHttpActionResult UpdateProperty( string propertyId, [FromBody] PropertyVM property )
{
bool success;
try
{
property.PropertyId = propertyId;
success = _inventoryDAL.UpdateProperty( property );
}
catch ( Exception ex ) when
(
ex is ArgumentException
|| ex is ArgumentNullException
|| ex is ArgumentOutOfRangeException
|| ex is FormatException
|| ex is NullReferenceException
|| ex is OverflowException
)
{
return BadRequest( ex.Message );
}
if ( !success )
{
return NotFound();
}
return Ok();
}
에 대한 잘못된 값으로 컨트롤러를 호출하면 컨트롤러 IsIncludedInSearch
에서을 잡을 것으로 예상 FormatException
했지만 발생하지 않습니다. 내 변환기에서 예외가 발생했지만 미디어 포맷터가 실행 중일 때 발생합니다. 컨트롤러에 들어갈 때 예외가 발생했지만 포착 할 수 없습니다. 그래서 나는 OK
나쁜 매개 변수를 가지고 있어도 돌아온다 .
적절한 응답을 반환 할 수 있도록 컨트롤러에서 변환기에서 예외가 발생했음을 확인하려면 어떻게해야합니까?
모델의 유효성 검사 오류 및 기타 속성 오류를 포함 할 모델 상태 오류를 확인해야합니다. 따라서 코드에서 다음과 같이 할 수 있습니다.
[HttpPost, Route("{propertyId}")]
public IHttpActionResult UpdateProperty(string propertyId,
[FromBody] PropertyVM property)
{
bool success = false;
if (ModelState.IsValid)
{
try
{
property.PropertyId = propertyId;
success = _inventoryDAL.UpdateProperty(property);
}
catch (Exception ex) //business exception errors
{
return BadRequest(ex.Message);
}
}
else
{
var errors = ModelState.Select(x => x.Value.Errors)
.Where(y => y.Count > 0)
.ToList();
return ResponseMessage(
Request.CreateResponse(HttpStatusCode.BadRequest, errors));
}
if (!success)
{
return NotFound();
}
return Ok();
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다