gpt4 book ai didi

ASP.Net Core razor 页面处理程序成为一条包罗万象的路线

转载 作者:行者123 更新时间:2023-12-05 07:13:06 25 4
gpt4 key购买 nike

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

最佳答案

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

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)
{
...
}
...

关于ASP.Net Core razor 页面处理程序成为一条包罗万象的路线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60240851/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com