ASP MVC C#: Is it possible to pass dynamic values into an attribute?

我们两清 提交于 2019-11-29 20:49:02

问题


Okay I'm very new to C# and i'm trying to create a little website using ASP MVC2.

I want to create my own authorization attribute. but i need to pass some values if this is possible.

For example:

    [CustomAuthorize(GroupID = Method Parameter?]
    public ActionResult DoSomething(int GroupID)
    {
        return View("");
    }

I want to authorize the access to a page. but it depends on the value passed to the controller. So the authorization depends on the groupID. Is this possible to achieve this in any way?.

Thanks in advance.


回答1:


Use the value provider:

public class CustomAuthorizeAttribute : FilterAttribute, IAuthorizationFilter
{
    public void OnAuthorization(AuthorizationContext filterContext)
    {
        var result = filterContext.Controller.ValueProvider.GetValue("GroupId"); //groupId should be of type `ValueProviderResult`

        if (result != null)
        {
            int groupId = int.Parse(result.AttemptedValue);

            //Authorize the user using the groupId   
        }
   }

}

This article may help you.

HTHs,
Charles




回答2:


You get it from Request.Form

public class CustomAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
       //httpContext.Request.Form["groupid"]
        return base.AuthorizeCore(httpContext);
    }
}



回答3:


You get it from Request.Form

public class CustomAuthorizeAttribute : AuthorizeAttribute { protected override bool AuthorizeCore(HttpContextBase httpContext) { //httpContext.Request.Form["groupid"] return base.AuthorizeCore(httpContext); } }



来源:https://stackoverflow.com/questions/2798516/asp-mvc-c-is-it-possible-to-pass-dynamic-values-into-an-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!