[英]Override routing in ASP.NET CORE 2.2 to implicitly route to an area if user have some permissions
I'm looking for an easy way to change routing behaviour a little and add extra area data into route data if the user has some sorts of permissions.如果用户具有某种权限,我正在寻找一种简单的方法来稍微改变路由行为并将额外的区域数据添加到路由数据中。
Let's say for regular user url site/shop/12
should route to ShopController
假设对于普通用户 url site/shop/12
应该路由到ShopController
but for admin it should route to AdminArea/ShopController
但对于管理员,它应该路由到AdminArea/ShopController
Please, consider that this question isn't about HTTP redirect, it's about extending infrastructure on a framework level to allow extra functionality on Routing or controller invocation请考虑这个问题不是关于 HTTP 重定向,而是关于在框架级别扩展基础设施以允许路由或控制器调用的额外功能
You could use URL Rewriting Middleware to redirect the request for Admin user您可以使用URL 重写中间件来重定向管理员用户的请求
1.Create a Redirect rule: 1.创建重定向规则:
public class RewriteRules
{
public static void RedirectRequests(RewriteContext context)
{
//Your logic
var IsAdminRole = context.HttpContext.User.IsInRole("Admin");
if (IsAdminRole)
{
var request = context.HttpContext.Request;
string area = "AdminArea";
var path = request.Path.Value;
//Add your conditions of redirecting
if(path.Split("/")[1] != area)// If the url does not start with "/AdminArea"
{
context.HttpContext.Response.Redirect($"/{area}{ request.Path.Value }");
}
}
}
}
2.Use the middleware in Startup Configure method: 2.在Startup Configure方法中使用中间件:
app.UseAuthentication();//before the Rewriter middleware
app.UseRewriter(new RewriteOptions()
.Add(RewriteRules.RedirectRequests)
);
Add logic to the controller method that handles site/shop/12
to check if the user is an admin, and if it is, redirect to to the proper admin area and controller.向处理site/shop/12
的控制器方法添加逻辑以检查用户是否是管理员,如果是,则重定向到正确的管理区域和控制器。
var isAdmin = IsUserAnAdmin();
if (isAdmin) {
// This will redirect to the Index method defined in the ShopController
// in the area name AdminArea
return RedirectToAction("Index", "Shop", new { Area = "AdminArea" });
}
I think the best way is to set the correct URLs on the front-end and then validate the request on the end-point doing something like this:我认为最好的方法是在前端设置正确的 URL,然后在端点上验证请求,执行如下操作:
[HttpGet]
[Route("v1.0/download/document")]
public IActionResult download_document(int id, string token)
{
try
{
if (token == null || isNotAdmin(token))
return Unauthorized();
That way your end-points are protected and you avoid redirections.这样您的端点就会受到保护,并且您可以避免重定向。 Plus, in my opinion everything makes a lot more sense on the front-end另外,在我看来,前端的一切都更有意义
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.