【问题标题】:ASP.Net Core razor page handler becomes a catch-all routeASP.Net Core razor 页面处理程序成为包罗万象的路线
【发布时间】:2020-05-31 02:39:08
【问题描述】:

我有一个简单的 ASP.Net Core 3.1 Razor Pages 项目。在 Index.cshtml 中,我已将 @page 更改为 @page "{handler?}",因此我可以使用基于路由的处理程序方法。这很好用。问题是,现在这个页面变成了任何 url 的包罗万象的路由。例如,我可以去http://mysite/foo,它不会再给出 404。如果处理程序方法不存在,如何使其返回 404?

【问题讨论】:

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


    【解决方案1】:

    我不知道这是否是最好的解决方案:

    public class IsValidPageHandler : ActionMethodSelectorAttribute 
        {
            public override bool IsValidForRequest(RouteContext routeContext, ActionDescriptor action)
            {
                if (!routeContext.RouteData.Values.ContainsKey("handler") 
                    || routeContext.RouteData.Values["handler"] == null 
                    || ((CompiledPageActionDescriptor) action).HandlerMethods.Any(f=>routeContext.RouteData.Values["handler"].ToString().Equals(f.Name, StringComparison.OrdinalIgnoreCase)))
                    return true;
                else
                    return false;
            }
        }
    

    然后

    ...
    endpoints.MapRazorPages();
    
    var actions = app.ApplicationServices.GetService<IActionDescriptorCollectionProvider>();
    foreach (var item in actions.ActionDescriptors.Items.Where(f => f.AttributeRouteInfo != null && f.AttributeRouteInfo.Template.Contains("{handler?}")).ToList())
        item.ActionConstraints.Add(new IsValidPageHandler());
    ...
    

    其他解决方案创建一个过滤器并添加过滤器,但稍后会在管道中发生。在你有 context.HandlerMethod 和 RouteData 的上下文,你可以比较类似于上面的内容

    public class CustomRazorPageFilter : IAsyncPageFilter
    {
        public Task OnPageHandlerSelectionAsync(PageHandlerSelectedContext context)
        { 
        ... 
        }
    ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-27
      • 2020-02-23
      • 2018-08-02
      • 1970-01-01
      • 2016-08-20
      • 2011-04-02
      • 2011-10-13
      • 1970-01-01
      相关资源
      最近更新 更多