.Net MVC 使用Areas后存在相同Controller时报错的解决办法; 从上下文获取请求的Area名及Controller名

先来说个额外的问题:如何在请求上下文(比如过滤器的中)获取请求对应的Area和Controller 名字?(假设请求上下文对象为 filterContext ):

1. 获取Area名 :

**(string)filterContext.RouteData.DataTokens["area"]**即可,

如果该请求不是对应Areas中的响应则DataTokens中不包含Key为"area"的键和值,则此处得到null。

2. 获取Controller名:

(string)filterContext.RouteData.Values["Controller"]

此处不通过DataTokens来获取,是因为当请求不是走Areas中的路由时,DataTokens中是不包含Key为"Controller"的键和值的。

.Net MVC项目添加区域后,如果使用的Controller与区域外的Controller重名时,默认路由未修改的情况下会出现该错误:

Multiple types were found that match the controller named 'XXX'. This can happen if the route that services this request ('{controller}/{action}/{id}') does not specify namespaces to search for a controller that matches the request. If this is the case, register this route by calling an overload of the 'MapRoute' method that takes a 'namespaces' parameter.

其实错误提示这里已经提示出了原因与解决方法:

问题原因:使用Areas后存在多个相同的Controller,路由注册未分开

解决方法:

分别修改 "RouteConfig.cs" 文件的 "RegisterRoutes" 方法 及 "XXXAreaRegistration.cs" 文件的 "RegisterArea" 方法, 添加namespaces指明各自的Controller对应的命名空间即可(其实就跟不同命名空间下存在相同类名是一样的道理):

相关推荐
想要一只奶牛猫5 小时前
Spring Web MVC(三)
前端·spring·mvc
独断万古他化15 小时前
【Spring Web MVC 入门实战】实战三部曲由易到难:加法计算器 + 用户登录 + 留言板全流程实现
java·后端·spring·mvc
csdnZCjava16 小时前
Spring MVC工作原理 及注解说明
java·后端·spring·mvc
想要一只奶牛猫16 小时前
Spring Web MVC(四)
前端·spring·mvc
qq_398898932 天前
【备忘】ASP.Net MVC无缝对接SQL Server数据库设置步骤
数据库·asp.net·mvc
苏婳6662 天前
Java---SSH(MVC)面试题
java·ssh·mvc
AI题库3 天前
1.3 ABP MVC开发环境搭建指南:从零开始快速上手
asp.net·mvc·.net·.netcore
独断万古他化5 天前
【Spring Web MVC 入门续篇】请求处理之 Cookie 与 Session 获取实战
后端·spring·java-ee·mvc
阿拉斯攀登6 天前
设计模式:Spring MVC 中命令模式的核心映射与设计逻辑
spring·设计模式·mvc·命令模式
七夜zippoe6 天前
Spring MVC请求处理流程源码分析与DispatcherServlet核心逻辑
java·spring·mvc·过滤器·拦截器