开发者

ASP MVC 3 - How to define a dynamic value to the base of url?

开发者 https://www.devze.com 2023-04-06 19:43 出处:网络
I would like to \"show\" a dynamic value to the base of the URL, so the url would be like this: host.com/SOME_VALUE/{area}/{controller}/{action}.

I would like to "show" a dynamic value to the base of the URL, so the url would be like this: host.com/SOME_VALUE/{area}/{controller}/{action}.

So, if a url without the first value (the dynamic value) is requested: host.com/{area}/{controller}/{action} the correct action should be called but when a view is rendered (or maybe when a redirect occurs) the correct url should be returned with the correct first value.

This solution would be useful only to show in the url a specified value the identifies the user logon, like the username or maybe the company name, or any other value rel开发者_开发技巧ated to the current session, this value won't be used to restricts access to the actions, so the both urls should be valid and call the same action on then same session:

host.com/{area}/{controller}/{action} host.com/some_value/{area}/{controller}/{action}

Any suggestions ?


This is completely untested but i'd have thought it would work...

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
        "MyRoute", // Route name
        "{somevalue}/{controller}/{action}/{id}", // URL with parameters
        new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );

    routes.MapRoute(
        "Default", // Route name
        "{controller}/{action}/{id}", // URL with parameters
        new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );

}

Would it be possible to add an additional static value to the URL when the somevalue part is used? i.e. host.com/users/some_value/area/controller/action. It would make the route mapping simple as all you'd need is:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
        "LoggedInUsers", // Route name
        "Users/{somevalue}/{controller}/{action}/{id}", // URL with parameters
        new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );

    routes.MapRoute(
        "Default", // Route name
        "{controller}/{action}/{id}", // URL with parameters
        new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );

}
0

精彩评论

暂无评论...
验证码 换一张
取 消