correct me on url routing in mvc

2019-07-22 20:37发布

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?

4条回答
相关推荐>>
2楼-- · 2019-07-22 20:50

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楼-- · 2019-07-22 20:51

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.

查看更多
The star\"
4楼-- · 2019-07-22 20:52

Easy - Put this before the default route above:

routes.MapRoute(
            "BigClientLogin", // Route name
            "Login", // URL with parameters
            new { controller = "Authentication", action = "BigClientLogin" } // Parameter defaults
        );
查看更多
【Aperson】
5楼-- · 2019-07-22 20:53

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(...)
查看更多
登录 后发表回答