correct me on url routing in mvc

2019-07-22 20:58发布

问题:

In my globas.asax file i have one register route

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

and in my action "BigClientLogin" it redirects to a new action called "NewLogin". So at present my current url looks like "http://localhost:65423/Authentication/NewLogin" .But i need my url in "http://localhost:65423/Login" format. To change action name from "NewLogin" to "Login" is not possible since i called this action many places in my solution. So is there any alternative solution for this in mvc routing? or is this is not possible and better will be to change my action name?

回答1:

A simple solution would be using the ActionName attribute. just put this on your action method

[ActionName("Login")]
public ActionResult NewLogin(...)
{
    ...
}

this would change only the Action Name, if you want only the path to be /login, use the Route attribute:

[Route("login", Name = "Login")]
public ActionResult NewLogin(...)


回答2:

A couple of options:

First, would be to map a route for this new login action:

routes.MapRoute(
  "NewLogin",
  "Login",
  new { controller = "Authentication", action = "NewLogin" }
);

Another option, if enabled, would be to leverage Attribute routing:

public class AuthenticationController : Controller
{
    [Route("~/Login", Name = "NewLogin")]
    public ActionResult NewLogin(...)
    {
        /* ... */
    }
}

(Just make sure routes.MapMvcAttributeRoutes() has been called in RouteConfig.cs)

With either of these, you'll have a named route you can reference in your solution (which will allow you to change it in the future if necessary):

@Html.RouteLink("Login", "NewLogin")


回答3:

You can try action aliases defined as attributes, see the article for further details: http://haacked.com/archive/2008/08/29/how-a-method-becomes-an-action.aspx/

[ActionName("View")]
public ActionResult ViewSomething(string id) {  
    return View();
}

The ActionNameAttribute redefines the name of this action to be “View”. Thus this method is invoked in response to requests for /home/view, but not for /home/viewsomething.



回答4:

Easy - Put this before the default route above:

routes.MapRoute(
            "BigClientLogin", // Route name
            "Login", // URL with parameters
            new { controller = "Authentication", action = "BigClientLogin" } // Parameter defaults
        );