为什么ASP.NET MVC Controller类需要是公共的? [英] Why do ASP.NET MVC Controller classes need to be public?

查看:103
本文介绍了为什么ASP.NET MVC Controller类需要是公共的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我更改控制器类的访问修饰符时,将导致错误.如果我将操作方法​​的可访问性设置为非公开,那么它还会导致错误(特别是找不到页面错误).为什么会这样?

When I make a change to the access modifier of a controller class it results in an error. If I make the accessibility of an action method non-public then it also results in an error (specifically a page not found error). Why is this the case?

推荐答案

默认情况下,如果未为类指定任何访问修饰符,则在C#中默认为internal.只有同一程序集中的代码才能访问internal的类.因此,如果您的控制器为internal,则在接收到请求时创建控制器实例的代码必须位于您的程序集中.

By default if you not specify any access modifier for a class then it will default to internal in C#. Only code in the same assembly can access a class that is internal. So if your controller is internal, the code that creates a controller instance upon receiving a request would have to be in your assembly.

但是System.Web.Mvc程序集中存在控制器创建代码,默认情况下DefaultControllerFactory负责创建控制器.例如,如果您的代码存在于MvcApplication1程序集中,则DefaultControllerFActory在没有公共访问修饰符的情况下无法找到您的控制器类,因此无法实例化它们.

But controller creation code is present in the System.Web.Mvc assembly and by default DefaultControllerFactory is responsible for creating controllers. If your code is present in, for example, the MvcApplication1 assembly then DefaultControllerFActory can not find your controller classes without the public access modifier so it is not able to instantiate them.

如果您想构建一个紧密耦合的ASP.NET MVC应用程序(不是它设计的),那么从理论上讲,您可以按照以下方式进行操作.

If you want to build a tightly coupled ASP.NET MVC application (which it is not it designed for) then theoretically you could do it following way.

  1. 获取MVC源代码(如果可用).
  2. 然后在同一程序集中构建代码.

这篇关于为什么ASP.NET MVC Controller类需要是公共的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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