简体   繁体   中英

MVC5 Route Doesn't Work

I recently upgraded from MVC 5 to MVC 3. I never registred a route, however, this URL worked:

http://www.testsite.com/shipworks/index/myemail@yahoo.com?website=testsite.com

Here is my code:

    [HttpPost]
    public ActionResult Index(string id, string website)
    {
        string data = string.Empty;
    }

I now get a 404 with this code. I tried this route, however, it also fails:

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

        routes.MapRoute(
"ShipWorks", // Route name
"{controller}/{action}/{id}/{website}", // URL with parameters
new { controller = "ShipWorks", action = "Index", email = UrlParameter.Optional, website =     
UrlParameter.Optional }, new[] { "CloudCartConnector.Web.Controllers" }// Parameter defaults
);

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

What am I doing wrong? I put the shipping route above the default one. Note that my id is a string. The URL works fine with ?id=myemail@myemail.com.

First approach.
According to your path:

"{controller}/{action}/{id}/{website}"

you don't need to specify explicitly "website" property name. Then, you marked in your route that {id} and {website} are separated by slash / , so correct use of your route mask should be http://www.testsite.com/shipworks/index/myemail@yahoo.com/testsite.com .
However, here is one problem - dot symbol . will not be recognized correctly (in the way you want). So if you remove the dot, the path http://www.testsite.com/shipworks/index/myemail@yahoo.com/testsitecom will work.

Second approach.
In order to reach the results you want, you'd better pass e-mail and website as the query parameter, not as the part of the path.
You can use the following route config:

routes.MapRoute(
    "ShipWorks", // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new
    {
        controller = "ShipWorks",
        action = "Index",
        id = UrlParameter.Optional
    }, new[] { "CloudCartConnector.Web.Controllers" }// Parameter defaults
);

Controller's action:

//[HttpPost]
public ActionResult Index(string email, string website)
{
    (...)
    return View();
}

And the query string: http://www.testsite.com/shipworks/index?email=myemail@yahoo.com&website=testsite.com .

Please note also, that since you marked your Index method with [HttpPost] attribute, you will get 404 using GET method (like typing in browser) even if you have correct URL.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM