在ASP.net 5 MVC 6中,如何在不同的命名空间中使用相同的控制器名称 [英] In ASP.net 5 MVC 6 , How to use same controller name in different namespaces

查看:192
本文介绍了在ASP.net 5 MVC 6中,如何在不同的命名空间中使用相同的控制器名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在不同的名称空间中定义了两个具有相同控制器名称的控制器.并得到了例外.如何使用参数"dataTokens"来定义像mvc-4这样的控制器的命名空间?

I defined two controller with same controller name in different namespaces. And got an exception. How to uer parameter "dataTokens" to define namespace of controller like mvc-4?

以下异常:

AmbiguousActionException: Multiple actions matched. The following actions matched route data and had all constraints satisfied:

Alice.Controllers.TestController.Index
Alice.Controllers.Api.TestController.Index
Microsoft.AspNet.Mvc.Infrastructure.DefaultActionSelector.SelectAsync(RouteContext context)

Controllers/Api/TestController.cs:

Controllers/Api/TestController.cs :

namespace Alice.Controllers.Api
{
    //[Route("api/[controller]")]
    public class TestController : Controller
    {
        //[Route("[action]")]
        public string Index()
        {
            return "this is controller at Alice.Controllers.Api"; ;
        }
    }
}

Controllers/TestController.cs:

Controllers/TestController.cs :

namespace Alice.Controllers
{
    //[Route("[controller]")]
    public class TestController : Controller
    {
        //[Route("[action]")]
        public string Index()
        {
            return "this is controller at Alice.Controllers";
        }
    }
}

Startup.cs

Startup.cs

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller}/{action}",
                defaults: null,
                constraints: null,
                dataTokens: new { Namespaces = new[] { "Alice.Controllers" } });

            routes.MapRoute(
                name: "api",
                template: "api/{controller}/{action}",
                defaults: null,
                constraints: null,
                dataTokens: new { Namespaces = new[] { "Alice.Controllers.Api" } });
        });

如果需要更多详细信息,请询问.

If more details need please ask.

推荐答案

不幸的是,默认情况下,您在ASPNET MVC区域(或区域和应用程序根目录之间)不能有重复的控制器名称.幸运的是,此问题的修复非常简单,并且异常描述了您需要执行的步骤.添加区域后,默认情况下,您将在两个不同的位置定义路由:一个在您的根应用程序中,另一个在您的区域注册中.您将需要调整它们两者以指定名称空间参数. 更多详细信息请点击此处

Unfortunately by default you cannot have duplicate controller names in ASPNET MVC Areas (or between an Area and the root of the application). Fortunately, the fix for this is pretty simple, and the exception describes the step you need to take. Once you’ve added an Area, you will have two different places (by default) where routes are defined: one in your root application and one in your area registration. You will want to adjust both of them to specify a namespace parameter. more details check here

这篇关于在ASP.net 5 MVC 6中,如何在不同的命名空间中使用相同的控制器名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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