[英]different route and auth for the same action in the .net core 2 mvc
I have an action in my ASP.NET Core controller. 我在ASP.NET Core控制器中有一个操作。 This action has multiple routes:
此操作有多个路线:
public class TestController
{
[HttpGet("test1")]
[HttpGet("test2")]
public async Task<object> Test()
{
//do something
}
}
These two routes require different access rights, the following: 这两条路由需要不同的访问权限,如下所示:
test/test1
need to have role1
permission test/test1
需要具有role1
权限 test/test2
need to have role2
permission test/test2
需要具有role2
权限 I'm override the HttpGet
class and implement IAuthorizationFilter
interface: 我重写
HttpGet
类并实现IAuthorizationFilter
接口:
public class AuthGet : HttpGet, IAuthorizationFilter
{
public AuthGet(string template,string roleName) : base(template)
{
}
public void OnAuthorization(AuthorizationFilterContext context)
{
//check auth
}
}
Then, I'm replacing HttpGet
with AuthGet
. 然后,我将
HttpGet
替换为AuthGet
。 This way, both AuthGet's OnAuthorization
will execute. 这样,两个AuthGet的
OnAuthorization
都将执行。 But I can't distinguish between test/test1
and test/test2
. 但是我无法区分
test/test1
和test/test2
。
How do I determine different permissions based on different routes on an Action
? 如何根据
Action
上的不同路由确定不同的权限?
There is no reason to keep this to a single method. 没有理由将其保留为单一方法。 Simply create
private
method to do the actual work and create two Actions that simply the return the value of that private
method: 只需创建
private
方法来完成实际工作,然后创建两个Action即可简单地返回该private
方法的值:
[AuthGet("test1", "role1")]
public async Task<object> Test1()
{
return await Test(1);
}
[AuthGet("test2", "role2")]
public async Task<IActionResult> Test2()
{
return await Test(2);
}
private async Task<object> Test(int testRoute)
{
if (testRoute == 1)
{
//do something
}
else
{
// do somthing else
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.