ASP.NET _ViewStart.cshtml-获取请求 [英] ASP.NET _ViewStart.cshtml - Getting the Request
问题描述
我有一个ASP.NET应用程序.我的应用程序具有_ViewStart.cshtml文件.该文件如下所示:
I have an ASP.NET app. My app has a _ViewStart.cshtml file. That file looks like this:
@using MyCompany.MyApp;
@{
Layout = "/Views/Shared/_Layout.cshtml";
var p = HttpContext.Current.Request.QueryString["parameter"];
ViewBag.QSParameter = p;
}
执行此代码时,出现以下错误:
When I execute this code, I get the following error:
The name 'HttpContext' does not exist in the current context
我不明白._ViewStart.cshtml是否不是视图的外壳"?我试图弄清楚如何全局读取查询字符串参数并为每个请求在ViewBag上设置一个值.我以为这是做到这一点的方法.
I don't understand. Isn't _ViewStart.cshtml kind of the "shell" for the views? I'm trying to figure out how to globally read a query string parameter and set a value on the ViewBag for each request. I thought this would be the way to do it.
谢谢
推荐答案
要从 _ViewStart.cshtml
检索它,可以使用:
To retrieve it from _ViewStart.cshtml
, you can use:
ViewBag.QSParameter = Context.Request.Query["parameter"];
注意:现在使用 Query
(通过ASP.NET 5中的 QueryString
)
但是,我可能会选择走一条不同的路线,并利用 IResultFilter
:
However, I might ellect to go a different route and take advantage of IResultFilter
:
public class QSParameterFilter : IResultFilter
{
public void OnResultExecuting(ResultExecutingContext context)
{
var QSParameter = context.HttpContext.Request.Query["parameter"];
((Controller)context.Controller).ViewBag.QSParameter = QSParameter;
}
public void OnResultExecuted(ResultExecutedContext context) { }
}
然后,在您的Startup.cs中注册它:
Then, register it within your Startup.cs:
services.AddMvc();
services.Configure<MvcOptions>(options => {
options.Filters.Add(new QSParameterFilter());
});
这篇关于ASP.NET _ViewStart.cshtml-获取请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!