简体   繁体   English

在IAsyncPageFilter-Asp.Net Core 2.0 Razor Pages中的OnPageHandlerExecutionAsync中,PageResult始终返回null

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

I'm using a ModelValidationFilter to handle model validation errors for all my post or put requests. 我正在使用ModelValidationFilter处理所有发布或放置请求的模型验证错误。 I'm using IAsyncPageFilter and registering as a global filter. 我正在使用IAsyncPageFilter并注册为全局过滤器。 In the OnPageHandlerExecutionAsync method, I'm able to handle the validation errors for ajax requests and send back a json response. 在OnPageHandlerExecutionAsync方法中,我可以处理Ajax请求的验证错误并发回json响应。 But for non ajax request, 但是对于非ajax请求,

I'm getting always null for var result = (PageResult)context.Result; 对于var result =(PageResult)context.Result ;,我总是总是为null。

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. OnPageHandlerExecutionAsync :在模型绑定完成之后,在调用处理程序方法之前异步调用

Which means that you don't have the Result available until after the OnGet/OnPost handlers are called. 这意味着直到调用OnGet / OnPost处理程序之后,您才可以使用结果 What you need to do is to get the underlying HandlerInstance from the context and cast it as a PageModel . 您需要做的是从上下文中获取基础HandlerInstance并将其PageModelPageModel You would now be able to access the ViewData and ContentType . 现在,您将可以访问ViewDataContentType

Then create your PageResult like below: 然后如下创建您的PageResult:

 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. 如果ModelState无效,则可能返回BadRequestObjectResult

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 . 创建PageResult时未设置页面,因此site can't be reached您到达site can't be reached的原因错误。 Instead, you can set the Response.StatusCode = 400 then call the result.Page() that will return the PageResult . 而是可以设置Response.StatusCode = 400然后调用PageResult result.Page()来返回PageResult I have tested the above code and it works. 我已经测试了上面的代码,并且可以正常工作。 I hope that helps. 希望对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM