Ich verwende einen benutzerdefinierten AuthorizationFilter wie folgt:
public class ActionAuthorizeAttribute : AuthorizeAttribute {
protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext) {
if(!httpContext.User.Identity.IsAuthenticated)
return false;
if(IsUserExcluded())
return false;
else
return IsRoleAuthorize(httpContext);
}
}
Ich verwende diesen Filter oben in jeder Aktion, die ich habe, und für die Überprüfung der Berechtigung ist der Aktionsname, der Controller-Name und der Bereichsname erforderlich. Gibt es eine Möglichkeit, diese Namen in AuthorizeCore()
-Methode zu erhalten, wie System.Web.HttpContextBase
? Wenn die Antwort Nein ist, wie kann ich diese Namen erhalten und an Attribute übergeben? Natürlich möchte ich nicht jeden Namen von Hand hinzufügen, eigentlich etwas wie ViewContext.RouteData.Values["Controller"]
in Controllern:
[ActionAuthorize(actionName=Action, controller=ControllerName, area=AreaName)]
public ActionResult Index() {
return View();
}
Hat jemand eine Ahnung davon?
Sie können sie von der RouteData abrufen:
protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext)
{
var rd = httpContext.Request.RequestContext.RouteData;
string currentAction = rd.GetRequiredString("action");
string currentController = rd.GetRequiredString("controller");
string currentArea = rd.Values["area"] as string;
...
}
Stellen Sie sich dem gleichen Problem vor einem Moment und meine Lösung ist:
Definieren Sie 2 Attribute in Ihrer ActionAuthorizeAttribute-Klasse, z.
public string ControllerName {get;set;}
public string ActionName {get;set;}
Geben Sie beim Kommentieren Ihrer Aktion des Controllers z.
[ActionAuthorize(Roles="Admin", ContollerName="ControllerName",ActionName="ActionName")]**
public ActionResult Disable(int id)
{
...
}
> namespace dene.kontroller {
> public class daAttribute: AuthorizeAttribute
> {
> private Entities db = new Entities();
> private readonly string[] allowedroles;
> public daAttribute(params string[] roles)
> {
> this.allowedroles = roles;
> }
>
>
> protected override bool AuthorizeCore(HttpContextBase httpContext)
> {
> bool authorize = false;
> foreach (var role in allowedroles)
> {
> if (role == HttpContext.Current.User.Identity.Name)
> {
>
> if (role!= null)
> {
> authorize = true;
> }
> }
>
>
> }
> return authorize;
> }
>
>
> protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
> {
>
> FormsAuthentication.SignOut();
> filterContext.Result = new HttpUnauthorizedResult();
> }
>
> } }
Das Abrufen des Bereichs funktioniert nicht, wenn Sie einen benutzerdefinierten Filter verwenden Mit dem nächsten wird ein Bereich erstellt
filterContext.RouteData.DataTokens["area"]