【问题标题】:MVC 4 Routing with UrlParameter.Optional expects parameter带有 UrlParameter.Optional 的 MVC 4 路由需要参数
【发布时间】:2012-11-30 03:50:56
【问题描述】:

在我的 MVC 解决方案中,我有不同的区域。该区域的注册之一是类如下所示。

 public class CommercialAreaRegistration : AreaRegistration
    {
        public override string AreaName
        {
            get
            {
                return "Commercial";
            }
        }

        public override void RegisterArea(AreaRegistrationContext context)
        {

            context.MapRoute(
                "Commercial_default",
                "Commercial/{controller}/{action}/{id}",
                new {  action = "Index", id = UrlParameter.Optional }
            );
        }
    }

基于此,url hxxp://localhost:63363/Commercial/VesselManagement 应该调用 VesselManagement 控制器的 Index 操作方法。它确实偶尔会按预期调用。但是现在它不执行 action 方法。

但是,如果我将 Url 键入为 hxxp://localhost:63363/Commercial/VesselManagement/index/abc,则会调用 Action 方法 Index 并传递参数 abs。

不仅对于这个操作方法,而且对于整个应用程序中的所有操作方法,都必须以这种模式调用 url。可能是什么问题。提前感谢大家的帮助。

注意:我用的是hxxp insted of http


Global.asx

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            //RouteDebug.RouteDebugger.RewriteRoutesForTesting(RouteTable.Routes);
            //Configure FV to use StructureMap
            var factory = new StructureMapValidatorFactory();

            //Tell MVC to use FV for validation
            ModelValidatorProviders.Providers.Add(new FluentValidationModelValidatorProvider(factory));
            DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
        }
    }

VesselManagement Index() 操作

public ActionResult Index()
        {

            InitialData();
            return View();
        }

注意:刚才我注意到索引不带任何参数,但我知道这会影响路由。

【问题讨论】:

  • 您能否展示您的其他路线,例如全球范围内的路线?我的猜测是一条不同的路线正在选择它,但如果没有更多上下文,我无法确定。
  • VesselManagement 的签名是什么? id 参数是可空类型吗?
  • hxxp://localhost:63363/Commercial/VesselManagement 被调用时找不到资源。 HTTP 404。您正在查找的资源(或其依赖项之一)可能已被删除、名称已更改或暂时不可用。请检查以下 URL 并确保其拼写正确。

标签: asp.net-mvc-4 asp.net-mvc-routing


【解决方案1】:

非常抱歉,这个问题是由于我的一位同事在创建区域时犯了一个错误,而对于区域注册,他错误地提到了路由规则。

 public class SharedAreaRegistration : AreaRegistration
    {
        public override string AreaName
        {
            get
            {
                return "Shared";
            }
        }

        public override void RegisterArea(AreaRegistrationContext context)
        {
            context.MapRoute(
                "Shared_default",
                "{controller}/{action}/{id}", //<---- This made the issue with routing

                new { action = "Index", id = UrlParameter.Optional }
            );
        }
    }

我是如何找出错误的,我将解释以下步骤,以便对您有所帮助。

首先我安装了Route Debugger

然后在 Global.asx 中编写 Application_Error 来处理错误。如果不写,Route Debugger 将无法找到路由。

protected void Application_Error(object sender, EventArgs e)
        {
            Exception exception = Server.GetLastError();
            // Log the exception.

            //ILogger logger = Container.Resolve<ILogger>();
           // logger.Error(exception);

            Response.Clear();

            HttpException httpException = exception as HttpException;

            RouteData routeData = new RouteData();
            routeData.Values.Add("controller", "Error");

            if (httpException == null)
            {
                routeData.Values.Add("action", "Index");
            }
            else //It's an Http Exception, Let's handle it.
            {
                switch (httpException.GetHttpCode())
                {
                    case 404:
                        // Page not found.
                        routeData.Values.Add("action", "HttpError404");
                        break;
                    case 500:
                        // Server error.
                        routeData.Values.Add("action", "HttpError500");
                        break;

                    // Here you can handle Views to other error codes.
                    // I choose a General error template  
                    default:
                        routeData.Values.Add("action", "General");
                        break;
                }
            }

            // Pass exception details to the target error View.
            routeData.Values.Add("error", exception);

            // Clear the error on server.
            Server.ClearError();

            // Avoid IIS7 getting in the middle
            Response.TrySkipIisCustomErrors = true;

            // Call target Controller and pass the routeData.
            //IController errorController = new ErrorController();
            //errorController.Execute(new RequestContext(
            //     new HttpContextWrapper(Context), routeData));
        }

然后我输入了 URL hxxp://localhost:63363/Commercial/VesselManagement 并且输出是

在输出的路由数据和数据令牌中明确表示它试图在共享区域内找到商业控制器和 VesselManagement ACtion。

错误的原因是错误地指定了共享区域路由,当通过在前面添加共享进行更正时,它得到了解决。

公共覆盖无效RegisterArea(AreaRegistrationContext上下文) { 上下文.MapRoute( "Shared_default", "共享/{controller}/{action}/{id}", 新 { action = "索引", id = UrlParameter.Optional } ); }

感谢 RouteDebugger

注意:路由从上到下工作,一旦找到匹配的路由,它将忽略其余部分。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-08
    • 2016-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-22
    相关资源
    最近更新 更多