我如何限制某些不使用的路线。
在我的startup.cs中,我有两个mapendpoint
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "botConfiguration",
pattern: "bot/{botID}/{controller=Home}/{action=Index}/{id?}");
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
在我的控制器中
public IActionResult Setting(int botID)
{
//botConfigRepository.GetAll();
return View();
}
我想说的是,如果我的路线中未定义botID,那么您将无法调用此操作,否则它将重定向到某种形式的主页。
现在我知道我可以
if (botID == 0 ){
return RedirectToAction("Index");
}
某种意义上,但为每一个动作写这个听起来很痛苦。
当然,ASP.NET Core支持多种实现跨领域关注点的方法。取决于您想要的程度,但是可以像添加自定义中间件委托一样简单,如下所示:
// In Startup.cs
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// Placed before app.UseEndpoints()
app.Use(async (ctx, next) => {
if (!ctx.Request.Query.ContainsKey("botID") && !ctx.Request.Path.Value.Contains("Index"))
ctx.Response.Redirect("Index");
else
await next();
});
}
(存在第二个条件只是为了防止级联重定向。)
中间件基本上是请求处理管道中最顶层的组成部分,本质上是一个责任链结构,每个中间件都可以通过它进行控制或短路。ASP.NET自己的组件被实现为中间件,例如授权中间件和路由中间件。这些添加到内部Startup.cs/Configure()
的顺序决定了它们的执行顺序。
因此,如果您想获得相对较低的水平,最干净的方法通常是使用中间件。您还可以添加适当的中间件类用app.UseMiddleware()
。
(您应该注意的一件事是中间件的寿命是单身,因此将请求范围的服务注入其中是有问题的。请参阅此问题。)
作为替代解决方案,您可以使用全局注册的方法ActionFilter
来达到相同的结果,就像有人评论的那样:
public class MyActionFilter : IActionFilter
{
public void OnActionExecuted(ActionExecutedContext context) {}
public void OnActionExecuting(ActionExecutingContext ctx)
{
if (!ctx.HttpContext.Request.Query.ContainsKey("botID") && !ctx.HttpContext.Request.Path.Value.Contains("Index"))
{
ctx.Result = new RedirectResult("Index");
}
}
}
// Register it in Startup.ConfigureServices()
services.AddMvc(options => options.Filters.Add(new MyActionFilter()));
如果您有其他要求,请随时发表评论,我可以尝试解决。:)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句