0

Upon login I want to re route to a new page. (Example: mysite.com/Dashboard/User/Username)

I also want it to verify that user is logged in before it allows access to said URL.

I'm new to MVC and C# and appreciate your help.

My controller: What do I pass into the controller to make it work?

public class DashboardController : Controller
{
    // GET: Dashboard
    public ActionResult User()
    {
        return View();
    }
}

Route.config.cs:

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
        routes.MapRoute(
            name: "UserNameRoute",
            url: "{username}",
            defaults: new { controller = "Dashboard", action = "User", username = "" }
        );
    }
}
NucleusDevelopment
  • 119
  • 1
  • 2
  • 12

1 Answers1

0

I believe it should be something like this:

routes.MapRoute(
    name: "UserNameRoute",
    url: "Dashboard/User/{username}",
    defaults: new { username = "" }
);
routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

I chose not to put the {controller} and {action} placeholders in the template as that would make it equal to the default route template. You could of course use just the action template if that is what you need:

routes.MapRoute(
    name: "UserNameRoute",
    url: "Dashboard/{action}/{username}",
    defaults: new { action = "User", username = "" }
);

Also note I put it before the default route because it is more specific. Otherwise the default route would catch every request.

Authorization is something you can't do here however. You will need to do that by e.g. creating a custom AuthorizeAttribute subclass that checks the username matches the logged in user.

juunas
  • 54,244
  • 13
  • 113
  • 149
  • 1
    `[Authorize]` isn't enough. That will only verify that *some user is logged in*, not necessarily the same user as specified in the URL. The OP will need a custom `[Authorize]` attribute that adds a check for that. Also, you should add sample code for how to redirect to that new route after the user signs in, since I think the OP doesn't know how to do that either. – Chris Pratt Feb 14 '17 at 19:39
  • I probably asked too much. I think I need to pass something into the following for the username to be passed through the controller, but not sure what: public class DashboardController : Controller { public ActionResult User() { return View(); } } – NucleusDevelopment Feb 14 '17 at 20:28
  • Your action needs a string parameter called username. – juunas Feb 14 '17 at 20:33