ASP.Net MVC:引发异常的路由问题 [英] ASP.Net MVC: Routing issue which throwing exception

查看:80
本文介绍了ASP.Net MVC:引发异常的路由问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个测试控制器,其中有一个索引动作,它接受 custid 作为参数.

I have a test controller where i have one index action which accept custid as a argument.

这就是我的控制器的外观

this is how my controller looks

public class TestController : Controller
{
    // GET: Test
    public ActionResult Index(int custid)
    {
        return View();
    }
}

我在route.config文件中添加了一条额外的路由语句.

i have added one extra routing statement in route.config file.

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

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

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

因此,当使用 localhost:50675/test/101 之类的URL访问测试控制器操作时,就会出错.错误消息说

so when accessing test controller action with url like localhost:50675/test/101 then getting error. error message say

参数字典包含参数'custid'的空条目方法的非空类型'System.Int32'的类型中的'System.Web.Mvc.ActionResult Index(Int32)''WebAPICRUD.Controllers.TestController'.可选参数必须是引用类型,可为null的类型或被声明为可选的范围.参数名称:参数

The parameters dictionary contains a null entry for parameter 'custid' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Index(Int32)' in 'WebAPICRUD.Controllers.TestController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter. Parameter name: parameters

但是当使用诸如 localhost:50675/test?custid = 101 之类的URL访问测试控制器操作时,不会出现任何错误.

but when accessing test controller action with url like localhost:50675/test?custid=101 then getting no error.

所以我不明白代码中有什么错误.

so i do not understand what mistake is there in code.

作为结果,我需要执行的操作可以发出此URL http://localhost:50675/test/101 应该可以.请指导我.谢谢

What i need to do as a result i can issue this url http://localhost:50675/test/101 which should work. please guide me. thanks

推荐答案

您的路线定义需要包含 custid (不是 id )的段,以匹配参数.路由定义还应包含控制器的名称,以使其唯一

Your route definition need to contain a segment for custid (not id) to match the name of the parameter. The route definition should also contain the name of the controller to make it unique

routes.MapRoute(
    name: "custom1",
    url: "Test/{custid}", // modify
    defaults: new { controller = "Test", action = "Index"}
);

请注意,您也可以删除 custid = UrlParameter.Optional ,因为您不希望它是可选的

Note that you can also remove the custid = UrlParameter.Optional since you do not want it to be optional

这篇关于ASP.Net MVC:引发异常的路由问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆