我有一个控制器,我想在默认情况下要求所有操作的授权,除了几个.因此,在下面的示例中,除了索引之外,所有操作都需要身份验证.我不想用Authorize来修饰每一个操作,我只想在某些情况下覆盖默认授权,可能是使用一个自定义过滤器,比如NotAuthorize.

[Authorize]
public class HomeController : BaseController
{
    [NotAuthorize]
    public ActionResult Index()
    {
        // This one wont
        return View();
    }

    public ActionResult About()
    {
        // This action will require authorization
        return View();
    }
}

推荐答案

好吧,我就是这么做的.如果有更好的方法,请告诉我.

public class NotAuthorizeAttribute : FilterAttribute
{
    // Does nothing, just used for decoration
}

public class BaseController : Controller
{
    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // Check if this action has NotAuthorizeAttribute
        object[] attributes = filterContext.ActionDescriptor.GetCustomAttributes(true);
        if (attributes.Any(a => a is NotAuthorizeAttribute)) return;

        // Must login
        if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
        {
            filterContext.Result = new HttpUnauthorizedResult();
        }
    }
}

Asp.net相关问答推荐

调用context.Users和context.Set User有什么区别?

如何在编译时为我的 ASP.NET 项目中的每个控制器生成一个单独的 OpenAPI Swagger.json 文件?

授权错误错误 400:C# 上的 redirect_uri_mismatch

我可以将图像添加到 ASP.NET 按钮吗?

如何在 IIS 上配置 Web Deploy 发布功能,以便开发人员可以发布?

如何从 JavaScript 调用 C# 函数?

在 aspx 页面中使用 if else 和 eval

如何删除字符串的定义部分?

ASP.NET Response.Redirect 使用 302 而不是 301

区分开发、登台和生产环境之间的 web.config

如何在asp.net中判断会话是否过期

返回值使用 String result=Command.ExecuteScalar() 结果返回 null 时发生错误

将存储过程中 Select 查询的结果返回到列表

asp.net 中的 Eval() 有什么用

使用 ASPNet_Regiis 加密自定义配置部分 - 你能做到吗?

如何在新实现的接口或基类之间做出决定?

修改 web.config 时如何防止 ASP.NET 应用程序重新启动?

如何使用 ASP.NET 和 jQuery 返回 JSON

DropDownList 的 SelectedValue 与 SelectedItem.Value

ASP.NET 网格视图与列表视图