How can I dynamically add RouteTable to ASP.NET MVC?

We have an area on our site where people can register and get their own page on the site that we want to place in ~ / pageSlug. I tried to do this using a rule in Global.asax, but this violated the default default route, which allows ~ / Controller to directly map the index action. I am not allowed to put any separator in front of userSlug, so ~ / p / pageSlug is actually not an option.

Regarding adding custom pages to routes, I look at the pages in App_Start and explicitly add them to RoutesTable. This works fine, and we have AppPool updates installed long enough to do it once a day. This leaves us with a 24-hour turn to “get pages live” for our users, although I'm trying to solve it.

Ideally, what I would like to do is add the appropriate route to RouteTable dynamically after the user has registered. I tried to do this with:

RouteTable.Routes.Add(
    RouteTable.Routes.MapRoute(
        toAdd.UrlSlug + "Homepage", 
        toAdd.UrlSlug, 
        new { controller = "Controller", View = "View", urlSlug = toAdd.UrlSlug }
    )
);

but that didn't seem to work. I can’t find a solution anywhere, and I’m sure that my code is terribly naive and betrays a lack of understanding of routing - please help!

+3
source share
3 answers

, , . ,

public class UserPageConstraint : IRouteConstraint
{
    public static IList<string> UserPageNames = (Container.ResolveShared<IUserService>()).GetUserPageNames();

    bool _IsUserPage;
    public UserPageConstraint(bool IsUserPage)
    {
        _IsUserPage = IsUserPage;            
    }

    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
    {
        if (_IsUserPage)
            return UserPageNames.Contains(values[parameterName].ToString().ToLower());
        else
            return !UserPageNames.Contains(values[parameterName].ToString().ToLower());
    }
}

Global.asax.cs :

routes.MapRoute("UserHome", "{userPage}", new { controller = "UserPageController", action = "Index" }, new { userPage = new UserPageConstraint(true) });

"index" UserPageController userPage .

HomePage Home . , userdetails :

routes.MapRoute("UserHome", "{userPage}/mydetails", new { controller = "UserPageController", action = "Details" }, new { userPage = new UserPageConstraint(true) });

.

+2

, , , , , Route Magic , , , - , . , ( , ).

routes.MapRoute(
  name: "ContactRequests_Operations",
  url: "ContactRequests-{operation}",
  defaults: new { controller = "Content", action = "Module_Direct", id =  "ContactRequests" , operation = "Get" }
  );

 routes.MapRoute(
    name: "Messages",
    url: "Messages",
    defaults: new { controller = "Content", action = "Direct", id ="Messages" }
);
+1

, .

, , : ASP.NET MVC

0

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


All Articles