Finding mvc3 action method parameters in user attribute

I am working on implementing user rights management in the mvc3 application.

I defined my database action methods with ControllerName, ActionName and Parameters: ParameterName and ParameterType etc.

I have implemented a custom attribute inherited from the Authorize attribute.

What I'm trying to do is find the action that is performed among my built-in actions defined in the database and calculate if the user has permission to the specified action or not.

The code is as follows:

[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 this is a post action. Added [HttpPost].

+4
source share
2 answers

I think reflection is the answer.

Once you have the controller and action, and if you know the namespace in advance, you can check the Type controller and move on to its methods and relative signatures / overloads.

Also, by checking the full contents of RouteData, in addition to the controller and the action, you can indicate that it is passed to the method.

I haven't tried it, but from what you say, it seems like it will work.

+2
source

I am not sure if I understood your question correctly. If you try to access the parameter values, I have an answer for you, if you really want to know the types of parameters, then @Matteo Mosca's answer will be correct:

It depends on where the parameters came from. Are they QueryString parameters or form parameters or cookies or ...

The ASP.NET middleware model attempts to map parameters in an action method. In your user attribution, you can access parameters with context, for example.

 string input = httpContext.Request.Form["myInput"] 

EDIT: This, of course, is not the most pleasant solution, because you need information about the placed parameters. Since I do not know your current requirements, I cannot offer a better offer. Of course, you can iterate through a collection of forms.

It may be possible that you are passing the field name as a parameter / property to MyAuthorizeAttribute.

+1
source

Source: https://habr.com/ru/post/1385496/


All Articles