PageResult always returns null in IAsyncPageFilter - OnPageHandlerExecutionAsync in Asp.Net Core 2.0 Razor Pages

孤街醉人 提交于 2019-12-08 09:39:22

问题


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();
}

回答1:


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.



来源:https://stackoverflow.com/questions/53984956/pageresult-always-returns-null-in-iasyncpagefilter-onpagehandlerexecutionasync

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!