MVC5.0 中如何提高Controller 的优先级

//在area下建立的Home
namespace WebApplication8.Areas.Weather.Controllers
{
    public class HomeController : Controller
    {
        // GET: Weather/Home
        public ActionResult Index()
        {
            return Content(this.GetType().FullName);
        }
    }
}

//在controller文件下建立的home
namespace WebApplication8.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
      
        public ActionResult Index()
        {
            return Content(this.GetType().FullName);
        }
    }
}

  运行时提示:

     

根据错误大家都知道是什么原因了,如何修改呢,有两种方法的,可能大家都知道是一种通过routeTable.Routes.MapRoute方法,进行namespaces约束,进行如:

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

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
                constraints: null,
                namespaces:new string[] { "WebApplication8.Areas.Weather.Controllers" }
            );
        }

  通过运行,果然可以识别正确的;

  

刚才说了还有另种方法来改变这种优先级;

  在controller中,有负责注册controller的controllerBuilder 类,通过他属性就可以达到注册,提升优先级的

如:

  protected void Application_Start()
        {
            ControllerBuilder.Current.DefaultNamespaces.Add("WebApplication8.Controllers");
            AreaRegistration.RegisterAllAreas();
            RouteConfig.RegisterRoutes(RouteTable.Routes);
        }

  结果:

     

,

    但是谁的优先级更高呢,我把正两种方法都一块,运行chrome,得知,通过路由的maproute注册的优先级更高。

 

posted @ 2016-01-05 22:11  Company  阅读(502)  评论(0编辑  收藏  举报