0

I have a controller called AccountController which handles user-related actions. I also defined a method:

//
// GET: /Account/Login
public ActionResult Login(string token)
{
    //logic here
}

Why the following URL without token specified would invoke the above action? http://localhost/Account/Login

I would expect URL like http://localhost/Account/Login?token=abcdefgh invoke the action ONLY.

This is my routing config:

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 }
        );
    }
}

Can anyone help? Thanks!

tereško
  • 58,060
  • 25
  • 98
  • 150
sc1013
  • 1,068
  • 2
  • 16
  • 24
  • Sorry I'm new to ASP.NET MVC. Can you suggest me how to do? I have updated my routing config above. Please see. – sc1013 Oct 17 '14 at 09:06

2 Answers2

0

As Login action GET http request type http://localhost/Account/Login matches action name works and pass null value to token parameter

asdf_enel_hak
  • 7,474
  • 5
  • 42
  • 84
0

Yes, it does kind of seem weird. Since C# has a nullable type, it would be nice if it accepted null when I specify string? token and forced me to specify a value when I specify string token.

That is why I like the new attribute based routing which exactly has that behavior. It has been bundled into the latest version of Web API. If you are using the old version still, you can use this Nuget package - http://attributerouting.net/

To force the user to specify token, you would write

[GET("account/token"]
public ActionResult Login(string token)
{
    //logic here
}

To make it optional, you would write

[GET("account/token?"]
public ActionResult Login(string token)
{
    //logic here
}
govin
  • 6,445
  • 5
  • 43
  • 56