为什么 Razor _layout.cshtml 在文件名中有一个前导下划线? [英] Why does Razor _layout.cshtml have a leading underscore in file name?

查看:15
本文介绍了为什么 Razor _layout.cshtml 在文件名中有一个前导下划线?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在默认的 ASP.NET MVC 3 项目中,布局 &部分 cshtml 文件以下划线开头

In the default ASP.NET MVC 3 project, layout & partial cshtml files start with an underscore

  • _viewstart
  • _Layout
  • _LogOnPartial

为什么要使用这个约定,它的用途是什么?我需要遵守这个约定吗?

Why this convention, and what is this used for? Do I need to follow this convention?

框架是否赋予以下划线开头的 .cshtml 文件一些特殊含义?

Does the framework give some special meaning to a .cshtml file that begins with an underscore?

推荐答案

Razor 是为 ASP.NET 网页 (WebMatrix) 开发的,它没有与您获得的关于视图文件夹和路由的相同类型的保护在MVC中.由于网页中的布局页面不打算直接提供服务,因此它们以下划线为前缀.并且网页框架已配置为不允许直接请求名称中带有前导下划线的文件.网页中的其他 .cshtml 文件通常需要可浏览.它们相当于 .asp 或 .php 文件.

Razor was developed for ASP.NET Web Pages (WebMatrix), which doesn't have the same sort of protection built in regarding Views folders and Routing that you get within MVC. Since layout pages in Web Pages are not intended to be served directly, they are prefixed with the underscore. And the Web Pages framework has been configured not to allow files with leading underscores in their names from being requested directly. Other .cshtml files within Web Pages generally need to be browsable. They are the equivalent of .asp or .php files.

ASP.NET 团队表示,网页是 ASP.NET 开发的起点,应该会及时迁移到 MVC(对于那些想要继续前进的人).这部分意味着从网页迁移到 MVC 应该尽可能容易.因此,将 Web Pages 中建立的命名约定转移到 MVC Razor 文件是有意义的.

The ASP.NET team have stated that Web Pages is a starting point within ASP.NET development, which should lead to migration to MVC in time (for those that want to move on). Part of that means that it should be as easy as possible to migrate from Web Pages to MVC. Consequently, it makes sense to carry over naming conventions established within Web Pages to MVC Razor files.

所以在文件名前加上下划线的技术原因 - 它只是与 MVC 无关.

So there is a technical reason for prefixing the file names with an underscore - it just isn't relevant to MVC.

[2018 年 10 月更新]

在新的 ASP.NET Core Razor Pages 框架(2.1 版除外)中,在启动时生成路由时,带有前导下划线的文件将被忽略 - 即使它们具有 @page指令(这通常会使它们成为可路由的 Razor 页面).这就是为什么在 Razor Pages 应用程序中命名布局和部分文件并带有前导下划线是有意义的,如果它们不打算被浏览.

In the new ASP.NET Core Razor Pages framework (apart from in version 2.1), files with a leading underscore are ignored when routes are being generated at startup - even if they have an @page directive (which would normally make them a routeable Razor Page). That's why it makes sense to name layout and partial files with a leading underscore in a Razor Pages application if they are not intended to be browsed.

这篇关于为什么 Razor _layout.cshtml 在文件名中有一个前导下划线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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