Reputation: 462
I am working on implementing user right management on an mvc3 application.
I have defined my action methods on database with ControllerName, ActionName, and Parameters consists ParameterName and ParameterType etc.
I implemented a custom attribute which inherited from Authorize attribute.
What i am trying to do is finding the action executing among my built-in actions defined on database and calculating if user has permission on specified action or not.
The code is like this;
[HttpPost]
[MyAuthorize]
public ActionResult Edit(VendorPageItem entity)
{
//...
}
public class MyAuthorize: System.Web.Mvc.AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if (httpContext == null)
throw new ArgumentNullException("httpContext");
string controller = httpContext.Request.RequestContext.RouteData.Values["controller"].ToString();
string action = httpContext.Request.RequestContext.RouteData.Values["action"].ToString();
int userId = SessionState.Current.LoginParameter.VendorUserID;
List<string> parameterTypes = new List<string>();
//TODO: Find out action method parameter types.
return IoCWorker.Resolve<IUserRightService>().HasUserRightToAction(userId, controller, action, parameterTypes);
}
}
My problem is finding the method parameter types in my custom attribute.
Thanks.
edit: forgot to mention that is post action. [HttpPost] added.
Upvotes: 4
Views: 1156
Reputation: 9129
I'm not sure whether I understood your question properly. If you try to access the parameter values, I have an answer for you, if you really want to know the parameter types, then @Matteo Mosca's answer will be correct:
That depends on where the parameters come from. Whether they are QueryString parameters or form parameters or cookies or...
The model binder infrastructure of ASP.NET tries to map the parameters on the action method. In your custom attribure you can access the parameters with the context, e.g.
string input = httpContext.Request.Form["myInput"]
EDIT: This is of course not the nicest solution because you need information about the posted parameters. As I don't know your real requirements, I can't make any better suggestion. Of course you could iterate through the Form collection.
A possiblilty could be that you pass the name of the field as a parameter/property of the MyAuthorizeAttribute.
Upvotes: 1
Reputation: 7448
I think reflection is the answer here.
Once you have the controller and the action, and assuming you know beforehand the namespace, you can inspect the controller Type
and drill down to its methods and relative signatures/overloads.
Also inspecting the full contents of RouteData apart from controller and action can tell you what it being passed to the method.
I haven't tried it out, but from what you say it seems it will work this way.
Upvotes: 2