ASP.NET _ViewStart.cshtml - Getting the Request

寵の児 提交于 2019-12-23 18:01:42

问题


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

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.

Thanks


回答1:


To retrieve it from _ViewStart.cshtml, you can use:

ViewBag.QSParameter = Context.Request.Query["parameter"];

Note: Use Query now (over QueryString) in ASP.NET 5

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) { }
}

Then, register it within your Startup.cs:

services.AddMvc();
services.Configure<MvcOptions>(options => {
  options.Filters.Add(new QSParameterFilter());
});



回答2:


You should have access to Request in your _ViewStart file.

Try this:

@using MyCompany.MyApp;
@{
  Layout = "/Views/Shared/_Layout.cshtml";

  var p = Request.QueryString["parameter"];
  ViewBag.QSParameter = p;
}

EDIT: For ASP.NET 5

I don't have ASP.NET 5 on my machine but have looked at the source code for the framework. It looks like there is a Context property on RazorPage that returns an HttpContext. Alternatively, you can access the HttpContext through the ViewContext. See below:

@{
  Layout = "/Views/Shared/_Layout.cshtml";

  var p = Context.Request.Query["parameter"];
  // or this...
  // var p = ViewContext.HttpContext.Request.Query["parameter"];
  ViewBag.QSParameter = p;
}


来源:https://stackoverflow.com/questions/32127261/asp-net-viewstart-cshtml-getting-the-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!