简体   繁体   中英

Marry RouteData.Values with Action Parameters

I'm setting some RouteData inside a custom Action Filter

filterContext.RouteData.Values.Add("accountId", accountId);
filterContext.RouteData.Values.Add("permission", (int)permission);

Then I have an action like the following

public ActionResult Get(Guid accountId, int permission, int id) {

}

Can I marry the RouteData values to the action parameters via a route? If so, how?

I'd like to just use an URL such as

http://localhost/Users/Get/1

They route data is present and can be retrieved by using

Guid accountId = (Guid)RouteData.Values["accountId"];
Permission permission = (Permission)RouteData.Values["permission"];

You should create a custom ValueProvider , not an action filter.
For more information, see here .

You could use the ActionParameters property:

public class MyActionFilterAttribute: ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        filterContext.ActionParameters["accountId"] = Guid.NewGuid();
        filterContext.ActionParameters["permission"] = 456;
    }
}

and then:

public class HomeController : Controller
{
    [MyActionFilter]
    public ActionResult Index(Guid accountId, int permission, int id)
    {
        return Content(string.Format("accountId={0}, permission={1}", accountId, permission));
    }
}

and when you request /home/index/123 the following is shown:

accountId=f72fddb8-1c35-467b-a479-b2668fd5b2ec, permission=456

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM