I'm using a ModelValidationFilter to handle model validation errors for all my post or put requests. I'm using IAsyncPageFilter and registering as a global filter. In the OnPageHandlerExecutionAsync method, I'm able to handle the validation errors for ajax requests and send back a json response. But for non ajax request,
I'm getting always null for var result = (PageResult)context.Result;
Please could you assist me on this?
I'm implementing this so that I don't need to write model validation in all post or put handlers in any razor page in my application.
Here is my implementation:
if (context.HttpContext.Request.Method.Equals("POST") || context.HttpContext.Request.Method.Equals("PUT"))
{
if (!context.ModelState.IsValid)
{
if (context.HttpContext.Request.IsAjaxRequest())
{
var errorModel = context.ModelState.Keys.Where(x => context.ModelState[x].Errors.Count > 0)
.Select(x => new
{
key = x,
errors = context.ModelState[x].Errors.Select(y => y.ErrorMessage).ToArray()
});
context.Result = new JsonResult(new AjaxResultHelper<IEnumerable<object>>
{
Response = errorModel,
Message = "_InvalidData_"
});
}
else
{
var result = (PageResult)context.Result;
context.Result = new PageResult
{
ViewData = result.ViewData,
ContentType = result.ContentType,
StatusCode = 400,
};
}
}
}
else
{
await next.Invoke();
}
According to the documentation
OnPageHandlerExecutionAsync : Called asynchronously before the handler method is invoked , after model binding is complete.
Which means that you don't have the Result available until after the OnGet/OnPost handlers are called. What you need to do is to get the underlying HandlerInstance
from the context and cast it as a PageModel
. You would now be able to access the ViewData
and ContentType
.
Then create your PageResult like below:
var result = context.HandlerInstance as PageModel; context.Result = new PageResult { ViewData = result.ViewData, ContentType = result.Request.ContentType, StatusCode = 400, };
Perhaps return the BadRequestObjectResult
if the ModelState
is invalid.
if (context.HandlerInstance is PageModel result) //using pattern matching
{
result.Response.StatusCode = 400;
context.Result = result.Page();
}
await Task.CompletedTask;
The reason you were getting the site can't be reached
error as there was no Page set when creating the PageResult
. Instead, you can set the Response.StatusCode = 400
then call the result.Page()
that will return the PageResult
. I have tested the above code and it works. I hope that helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.