Web.Config 文件在 MVC 项目的视图文件夹中做什么

我在部署应用程序时遇到了一些问题,在进行故障排除时,我在 Views文件夹中发现了 Web.Config文件。为了缩小我的问题来源的可能性,我试图找出那个网站的目的。配置文件,但实际上找不到太多信息。

所以基本上我的问题是:

  1. Web.config文件在 MVC 项目的 Views文件夹中做什么?
  2. 有必要吗?

在阿斯珀。我认为,要在一个文件夹中使用一个单独的 web.config 文件,该文件夹必须在 IIS 中设置为一个虚拟文件夹。在 MVC 中是这种情况吗(即 Views文件夹是否需要配置为虚拟文件夹) ?

41792 次浏览

No, you do not need to configure a virtual folder because of this extra web.config file.

The web.config file exists in the Views folders to prevent access to your views by any means other than your controller. In the MVC design pattern, controllers are supposed to route requests and return a rendered view to the calling client.

In other words, your view at www.mydomain.com/MySuperController/AwesomeAction1/SweetPage.aspx should not be directly accessible.

If you peek at the web.config file it actually registers the HttpNotFoundHandler to all paths and verbs:

<add path="*" verb="*" type="System.Web.HttpNotFoundHandler"/>

Or, in IIS 7 it might look like

<add name="BlockViewHandler" path="*.aspx" verb="*"
preCondition="integratedMode" type="System.Web.HttpNotFoundHandler"/>

It configures the compiler for the views such as importing namespaces and makes the views folder return a 404.

That's if you want to override something mentioned in the upper web.config, i.e. if you want to customize something within the scope of the Views folder.

The web.config file in the views folder is to do some specialized settings you want to apply to pages inside the view folder.

Like config settings like: connection string / appsettings etc.

but that will be applicable to only that folder and rest of the project will pick up the settings from web.config present at the root.

Specially when you use concept of area there will be separate folder for each area containing separate web.cfg file where you can apply separate settings for each area.