简体   繁体   中英

Passing a non numeric value for default “id” parameter in MVC Controller

I have a fairly simple setup where I am creating a MVC website to display the details of a customer. For customers the unique id is their email address which is non-numeric. So in my ROuteConfig.cs I have the default route

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

In my controller called "CustomerController" I have this action

public ActionResult Details(string id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            CustomerModel customerModel = _customerManager.GetCustomer(id);
            if (customerModel == null)
            {
                return HttpNotFound();
            }
            return View(customerModel);
        }

Now when I navigate to this url

http://localhost:45826/customer/Details/someemail%40web.com

the routing infrastructure does not invoke the Action "Details" on my controller, however if I navigate to this url

http://localhost:45826/customer/Details/5

then the action is invoke passing in the value 5 for the id parameter.

If I change the URL a bit and use this syntax

http://localhost:45826/customer/Details?id=fromweb%40web.com

Again the action is invoked properly passing the email address to the id parameter.

Can someone help understand why non-numeric values aren't mapping to the action as expected?

I have also tried adding this route before the default route but that doesn't work too and I get same results

routes.MapRoute(
            name: "ViewCustomer",
            url: "customer/details/id",
            defaults: new { controller = "Customer", action = "Details", id = "" }
            );

Add this in web.config:

<system.webServer>
    <modules runAllManagedModulesForAllRequests="true">

Read: https://stackoverflow.com/a/49831093/10299573

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