ASP.NET Core MVC 中 Layout.cshtml 中的访问请求或 IQueryCollection?

use*_*993 4 asp.net asp.net-core-mvc asp.net-core

是否可以在视图中访问RequestIQueryCollection,特别是在_Layout.cshtml? 这样做的原因是根据查询字符串有条件地渲染 Razor 中的元素。显然这并不理想,但这是一个遗留应用程序。

Kir*_*kin 9

您可以IQueryCollection通过Context属性访问任何 Razor 视图的内部,该属性是HttpContext. 下面是一个例子:

<p>Foo: @Context.Request.Query["Foo"]</p>
Run Code Online (Sandbox Code Playgroud)

请参阅此处的文档:Use HttpContext from a Razor view