Search code examples
c#asp.net-mvcasp.net-mvc-routing

MVC URL re-writing


I have Login action method in my home controller like this

 [HttpGet]        
        public ActionResult Login()
        {
            return View();
        }

I am having this Action method as start page of my application, however I want to re-write it like this www.abc.com/MySite/security/login

I write this attribute after [HttpGet]

   [Route("MySite/security/Login")]

Now the problem is,when I am running the application,its giving me error

The resource cannot be found.

This is my RoutConfig

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

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


        }

How can I fix this issue,Also I am having same name method with HttpPost attribute,should I have to write Rout Attribute on it as well?


Solution

  • This should do the work:

    [RoutePrefix("MySite/Security")]
        public class HomeController : Controller
        {
            public ActionResult Index()
            {
                return View();
            }
    
            [HttpGet]
            [HttpPost]
            [Route("Login")]
            public ActionResult Login()
            {
                return View("~/Views/Home/Index.cshtml");
            }
        }
    

    EDITED:

    There is one way, but I'm not sure if it's the best way. You need to create another controller called DefaultController like this:

    public class DefaultController : Controller
        {
            //
            // GET: /Default/
            public ActionResult Index()
            {
               return RedirectToAction("Login","Home");
            }
        }
    

    In your RouteConfig.cs, change the 'Default' route with this:

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

    This should do the job. I'm still trying to find other better ways.