asp.net-mvc 在 razor view .net core 2 中访问会话变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46921275/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Access session variable in razor view .net core 2
提问by Ella
I'm trying to access session storage in a razor view for a .net core 2.0 project. Is there any equivalent for @Session["key"] in a .net 2.0 view? I have not found a working example of how to do this - I am getting this error using the methods I have found:
我正在尝试在 .net core 2.0 项目的剃刀视图中访问会话存储。在 .net 2.0 视图中是否有任何等效的 @Session["key"] ?我还没有找到如何执行此操作的工作示例 - 我使用我找到的方法收到此错误:
An object reference is required for the non-static field, method, or propery HttpContext.Session
非静态字段、方法或属性 HttpContext.Session 需要对象引用
View:
看法:
@using Microsoft.AspNetCore.Http
[HTML button that needs to be hidden/shown based on trigger]
@section scripts {
<script>
var filteredResults = '@HttpContext.Session.GetString("isFiltered")';
</script>
}
Startup.cs:
启动.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddSession(options => {
options.IdleTimeout = TimeSpan.FromMinutes(30);
});
services.AddMvc();
// Added - uses IOptions<T> for your settings.
// Added - replacement for the configuration manager
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
//exception handler stuff
//rewrite http to https
//authentication
app.UseSession();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
回答by Shyju
You can do dependency injection in views, in ASP.NET Core 2.0 :)
您可以在 ASP.NET Core 2.0 中的视图中进行依赖注入:)
You should inject IHttpContextAccessorimplementation to your view and use it to get the HttpContextand Sessionobject from that.
您应该将IHttpContextAccessor实现注入您的视图并使用它来从中获取HttpContext和Session对象。
@using Microsoft.AspNetCore.Http
@inject IHttpContextAccessor HttpContextAccessor
<script>
var isFiltered = '@HttpContextAccessor.HttpContext.Session.GetString("isFiltered")';
alert(isFiltered);
</script>
This should work assuming you have the relevant code in the Startup.csclass to enable session.
假设您在Startup.cs类中有相关代码来启用会话,这应该有效。
public void ConfigureServices(IServiceCollection services)
{
services.AddSession(s => s.IdleTimeout = TimeSpan.FromMinutes(30));
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseSession();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
To set session in a controller, you do the same thing. Inject the IHttpContextAccessorto your controller and use that
要在控制器中设置会话,您需要做同样的事情。将 注入IHttpContextAccessor您的控制器并使用它
public class HomeController : Controller
{
private readonly ISession session;
public HomeController(IHttpContextAccessor httpContextAccessor)
{
this.session = httpContextAccessor.HttpContext.Session;
}
public IActionResult Index()
{
this.session.SetString("isFiltered","YES");
return Content("This action method set session variable value");
}
}
Use Session appropriately. If you are trying to pass some data specific to the current page, (ex : Whether the grid data is filtered or not , which is very specific to the current request), you should not be using session for that. Consider using a view model and have a property in that which you can use to pass this data. You can always pass these values to partial views as additional data through the view data dictionary as needed.
适当地使用 Session。如果您试图传递一些特定于当前页面的数据(例如:网格数据是否被过滤,这是非常特定于当前请求的),您不应该为此使用会话。考虑使用视图模型并在其中具有可用于传递此数据的属性。您始终可以根据需要通过视图数据字典将这些值作为附加数据传递给部分视图。
Remember, Http is stateless. When adding stateful behavior to that, make sure you are doing it for the right reason.
请记住,Http 是无状态的。在向其添加有状态行为时,请确保您出于正确的原因这样做。
回答by Mawardy
put this at the top of the razor page
把它放在剃须刀页面的顶部
@using Microsoft.AspNetCore.Http;
then you can easily access session variables like that
然后您可以轻松访问这样的会话变量
<h1>@Context.Session.GetString("MyAwesomeSessionValue")</h1>
if you get null values , make sure you include that in your Startup.cs
& make sure that options.CheckConsentNeeded= context is set to false
For more information about CheckConsentNeeded check this GDPR
如果您得到空值,请确保将其包含在您的 Startup.cs 中
& 确保选项。CheckConsentNeeded= 上下文设置为false
有关 CheckConsentNeeded 的更多信息,请查看此GDPR
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
//options.CheckConsentNeeded = context => true;
options.CheckConsentNeeded = context => false;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddDistributedMemoryCache();
services.AddSession(options =>
{
// Set session timeout value
options.IdleTimeout = TimeSpan.FromSeconds(30);
options.Cookie.HttpOnly = true;
});
}
Also make sure you are adding app.UseSession();to your app pipeline in Configure function
还要确保您正在添加app.UseSession(); 到配置函数中的应用程序管道
for more info about Sessions in Asp.net Core check this link Sessions in Asp.net Core
有关 Asp.net Core 中会话的更多信息,请查看此链接Asp.net Core 中的会话
tested on .net core 2.1
在 .net core 2.1 上测试
回答by Ella
As others have mentioned, I think the real solution here is not to do this at all. I thought about it, and while I have a good reason for using the session, since the razor tags are only useful for the initial page load anyway it makes more sense to just populate the view model in the controller with the stored session values.
正如其他人所提到的,我认为真正的解决方案是根本不这样做。我想了想,虽然我有一个很好的理由使用会话,因为 razor 标签只对初始页面加载有用,所以只用存储的会话值填充控制器中的视图模型更有意义。
You can then pass the view model with the current session values to your view, and access your model instead. Then you don't have to inject anything into your view.
然后,您可以将带有当前会话值的视图模型传递给您的视图,并改为访问您的模型。然后你不必在你的视图中注入任何东西。

