简体   繁体   English

在MVC Controller中为默认的“ id”参数传递非数值

[英]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. 我有一个相当简单的设置,我在其中创建一个MVC网站来显示客户的详细信息。 For customers the unique id is their email address which is non-numeric. 对于客户,唯一的ID是其非数字电子邮件地址。 So in my ROuteConfig.cs I have the default route 所以在我的ROuteConfig.cs中,我有默认路由

 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 在名为“ CustomerController”的控制器中,我有此操作

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 现在,当我导航到该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 路由基础结构不会在我的控制器上调用操作“详细信息”,但是如果我导航到该URL

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

then the action is invoke passing in the value 5 for the id parameter. 然后调用该操作,将id参数的值传递为5。

If I change the URL a bit and use this syntax 如果我稍微更改URL并使用此语法

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

Again the action is invoked properly passing the email address to the id parameter. 再次调用该操作,将电子邮件地址正确传递给id参数。

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: 在web.config中添加它:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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