.netコア2.xプロジェクトで動作しています。 私のモデルステートを検証するために、以下のコードを各アクションに記述します。.net coreコントローラ/アクションでModelStateを繰り返さないようにしてください。
if (ModelState.IsValid)
{
// Do something
}
else
{
// Return Modelstate Error
}
各アクションで条件を繰り返さないようにするためのベストプラクティスを知りたいと思います。 アクションに到達する前にmodelstateを検証し、modelstateが有効でない場合は適切なエラーメッセージを返します。
更新
注意。私のアクションは単純なAPIアクションであり、私はちょうどHttpContext Body内のエラー(私のモデルにある)を文字列の配列の形で返そうとしています。
例:モデルプロパティ。
[Required(ErrorMessage = "Fill the name Please !!!")]
public string FirstName { get; set; }
アクションの例この
public class ModelStateValidationFilter : ActionFilterAttribute
{
public string ErrorPage;
public override void OnActionExecuting(ActionExecutingContext context)
{
if (!context.ModelState.IsValid)
{
//return error result
List<string> list = (from modelState in context.ModelState.Values from error in modelState.Errors select error.ErrorMessage).ToList();
context.Result = new BadRequestObjectResult(list);
//or redirect to some result
context.Result = new RedirectToRouteResult(ErrorPage);
//or do whatever you need
}
base.OnActionExecuting(context);
}
}
よう
[HttpPost]
public void Create([FromBody]MyModel model)
{
if (ModelState.IsValid)
{
// Do something
}
else
{
// Return Modelstate Error
}
}
これをチェックしてくださいhttps://www.jerriepelser.com/blog/validation-response-aspnet-core-webapi/ –