【问题标题】:Short Circuit the Pipeline in Razor Pages使 Razor 页面中的管道短路
【发布时间】:2019-01-22 10:56:35
【问题描述】:

我希望在 .Net Core 2.1 Razor 页面中短路管道。具体来说,如果在没有模型绑定或在页面方法中运行任何代码的情况下满足某个条件,我希望重定向到另一个页面。在下面的示例中,重定向发生但仅在页面方法中的所有内容都完成后发生。

public class TestModel : PageModel
{
    public async Task<IActionResult> OnGetAsync()
    {
        //This line will still run after the redirect called from within OnPageHandlerSelectionAsync.
        var test = 0;

        return Page();
    }

    public async Task<IActionResult> OnPostAsync()
    {
        //This line will still run after the redirect called from within OnPageHandlerSelectionAsync.
        var test = 0;

        return Page();
    }

    public override async Task OnPageHandlerSelectionAsync(PageHandlerSelectedContext context)
    {
        if (true)//Some page specfic check, i.e. this will redirect to index page after 3PM.
        {
            //This line gets hit before OnGetAsnyc/OnPostAsync is called. 
            context.HttpContext.Response.Redirect("/Index");
        }
    }
}

This page is the link for the Razor Page filter docs 但它指的是the MVC documentation 用于管道短路/取消。不幸的是,MVC 过滤器页面上的标题警告该页面的文档不适用于剃须刀页面。

一旦在页面选择时满足条件,如何让页面放弃运行更多代码?

*在声明中未找到该条件,因此不会应用自定义授权过滤器。

【问题讨论】:

    标签: razor asp.net-core-2.0 razorengine razor-pages


    【解决方案1】:

    您可以执行以下操作。这在 3.1 版本中对我有用。

    public void OnPageHandlerExecuting(PageHandlerExecutingContext context)
    {
         if (condition is true)
         {                            
              context.Result = new RedirectResult(yourpagename);
         }
    }
    

    【讨论】:

      【解决方案2】:

      对于短路,您可以尝试Middleware并根据您自己的逻辑检查请求,如下所示:

              app.Use(async (context,next) => {
                  if (context.Request.Path.StartsWithSegments(new PathString("/Product")))
                  {
                      context.Response.Redirect("/Index");
                  }
                  await next();
              });
              app.UseMvc();
      

      注意,在调用app.UseMvc();之前使用Middlware

      【讨论】:

        【解决方案3】:

        不支持 Razor 页面过滤器内的短路或取消。您需要通过Resource Filters 来实现它。

        See here 了解如何在资源过滤器中进行操作

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-09-28
          • 1970-01-01
          • 2018-10-16
          • 2023-03-24
          • 2019-05-22
          • 1970-01-01
          • 2021-10-02
          • 2020-05-06
          相关资源
          最近更新 更多