剃刀页面中的管道短路

时间:2018-08-15 14:36:53

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

我正在寻找使.Net Core 2.1 Razor Page中的管道短路的方法。具体来说,如果没有模型绑定或运行页面方法中的任何代码,如果满足特定条件,则希望重定向到另一个页面。在下面的示例中,重定向仅在完成page方法中的所有操作之后发生。

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过滤器页面上的标题警告该页面的文档不适用于剃须刀页面。

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

*在声明中找不到该条件,因此自定义“授权”过滤器将不适用。

3 个答案:

答案 0 :(得分:1)

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

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

注意,请在致电Middlware之前使用app.UseMvc();

答案 1 :(得分:0)

不支持在Razor Page过滤器内部进行短路或取消。您需要通过Resource Filters来实现。

See here,了解如何在资源过滤器中实现

答案 2 :(得分:0)

您可以执行以下操作。这对我来说是3.1版本。

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