Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/319.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用属性访问配置文件_C#_Asp.net_Custom Attributes - Fatal编程技术网

C# 使用属性访问配置文件

C# 使用属性访问配置文件,c#,asp.net,custom-attributes,C#,Asp.net,Custom Attributes,在我的网站上,我有不同的页面,具有不同级别的访问权限。通常,我会用一些东西: if(!user.IsAdministrator) return RedirectToAction("AccessDenied", "Security"); 但我意识到这将我与我预先构建的安全级别捆绑在一起;事实上,我想要的是一个完全可定制的访问方案 我考虑的一个解决方案是,在我想要授予受限访问权限的操作中设置一些属性,然后检索它们放置的位置。我对属性(至少是自定义属性)没有什么经验,尽管我知道如何列出所有被

在我的网站上,我有不同的页面,具有不同级别的访问权限。通常,我会用一些东西:

if(!user.IsAdministrator)
    return RedirectToAction("AccessDenied", "Security");
但我意识到这将我与我预先构建的安全级别捆绑在一起;事实上,我想要的是一个完全可定制的访问方案

我考虑的一个解决方案是,在我想要授予受限访问权限的操作中设置一些属性,然后检索它们放置的位置。我对属性(至少是自定义属性)没有什么经验,尽管我知道如何列出所有被标记的操作,但我仍然在努力构思一种检查正确访问权限并拒绝访问的方法


有关于这个问题的线索吗?我还想知道是否有处理此问题的标准做法。

通常在ASP.NET MVC中,Authorize属性可用于此目的

您可以从中派生并重写AuthorizeCore方法以满足您的需要。然后可以使用此属性标记MVC操作或整个MVC控制器。或者更好的是,您可以将其配置为全局过滤器,这样它将自动为所有控制器启用。然后,可以使用AllowAnonymous属性标记您不希望受保护的操作:

这里有一篇文章已经讨论了这个属性

你可以在网上找到更多关于这个话题的文章

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        if (filters != null)
        {
            filters.Add(new CustomAuthorizeAttribute());
        }
    }


[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public sealed class CustomAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        //your code here
    }