【发布时间】:2019-02-24 10:01:16
【问题描述】:
我正在使用“授权”
来自:System.Web.Http
基本控制器的属性。
问题是我需要根据情况使用它。
(假设我有一个不需要身份验证/授权的模式)。
我怎样才能实现它?
谢谢。
【问题讨论】:
标签: c# asp.net-web-api2 custom-attributes
我正在使用“授权”
来自:System.Web.Http
基本控制器的属性。
问题是我需要根据情况使用它。
(假设我有一个不需要身份验证/授权的模式)。
我怎样才能实现它?
谢谢。
【问题讨论】:
标签: c# asp.net-web-api2 custom-attributes
一种方法是覆盖AuthorizeAttribute,并在其中添加自定义逻辑。
这里我们有两种情况,如果你想将它与MVC 控制器一起使用覆盖AuthorizeCore() 方法并使用System.Web.Mvc 命名空间,如下所示:
public class MyCustomAuthorizeAttribute: AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var authorized = base.AuthorizeCore(httpContext);
bool isExceptionalCase = GetIfExceptional();//Assuming here where you look for some other condition other than user is authorized
if (!isExceptionalCase && !authorized)
{
// The user is not authorized => no need to go any further
return false;
}
return true;
}
}
第二种情况,在您的情况下,您将使用 WebApi 控制器,您可以覆盖 IsAuthorized() 并使用 System.Web.Http 命名空间:
public class MyCustomAuthorizeAttribute : AuthorizeAttribute
{
protected override bool IsAuthorized(System.Web.Http.Controllers.HttpActionContext actionContext)
{
var authorized = base.IsAuthorized(actionContext);
bool isExceptionalCase = GetIfExceptional();//Assuming here where you look for some other condition other than user is authorized
if (!isExceptionalCase && !authorized)
{
// The user is not authorized => no need to go any further
return false;
}
return true;
}
}
然后在动作或控制器上使用自定义属性,而不是使用标准属性:
[MyCustomAuthorize]
public ActionResult MyAction()
{
...
}
【讨论】:
override bool AuthorizeCore 不适合你? @user10776203
您可以在特定方法或控制器中使用 AllowAnonymousAttribute 来“覆盖”基本控制器中使用的 AuthorizeAttribute。
查看参考:https://docs.microsoft.com/en-us/previous-versions/aspnet/hh835113(v%3dvs.118)
作为另一种选择,您可以创建自定义属性并在基本控制器中使用它。通过这种方式,您可以在自定义属性中添加做出决策所需的所有逻辑。
查看参考:https://docs.microsoft.com/en-us/dotnet/standard/attributes/writing-custom-attributes
问候,洛杉矶。
【讨论】: