c# - 如何根据条件使用属性。(通过标志禁用)
问题描述
我正在使用来自:System.Web.Http
基本控制器的属性。
问题是我需要根据条件使用它。
(假设我有一种不需要身份验证/授权的模式)。
我怎样才能实现它?
谢谢。
解决方案
一种方法是覆盖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()
{
...
}
推荐阅读
- reactjs - 在没有消费者的情况下使用 contexProvider 会被认为是不好的做法吗
- javascript - 如何从 Node.js 中的回调函数中获取返回值?
- php - 类 google.cloud.speech.v1.LongRunningRecognizeMetadata 尚未添加到描述符池
- bash - Bash 脚本将单个文件从一个 S3 存储桶复制 100 次到另一个并行
- java - 使用 IBM Java 显示西里尔字符串的问题
- python - 在 django 中提交表单时如何传递当前登录的用户?
- tableau-api - 如何在画面中创建重置按钮?
- email - 使用 STARTTLS 在 FusionAuth 中发送电子邮件
- sql - 如何从考勤日志中生成第一个 IN 和最后一个 OUT
- azure - 使用 ADF v2 将“获取元数据”活动输出到 SQL 表