在 razor view .net core 2 中访问会话变量
Access session variable in razor view .net core 2
我正在尝试在 razor 视图中访问 .net core 2.0 项目的会话存储。在 .net 2.0 视图中是否有任何等效于 @Session["key"] 的东西?我还没有找到如何执行此操作的工作示例 - 我使用找到的方法遇到此错误:
An object reference is required for the non-static field, method, or propery HttpContext.Session
查看:
@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:
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?}");
});
}
你可以在视图中进行依赖注入,在 ASP.NET Core 2.0 :)
您应该将 IHttpContextAccessor
实现注入到您的视图中,并使用它从中获取 HttpContext
和 Session
对象。
@using Microsoft.AspNetCore.Http
@inject IHttpContextAccessor HttpContextAccessor
<script>
var isFiltered = '@HttpContextAccessor.HttpContext.Session.GetString("isFiltered")';
alert(isFiltered);
</script>
假设您在 Startup.cs
class 中有相关代码以启用会话,这应该可以工作。
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?}");
});
}
要在控制器中设置会话,您需要做同样的事情。将 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");
}
}
适当使用 Session。如果您试图传递一些特定于当前页面的数据,(例如:网格数据是否被过滤,这对当前请求非常特定),您不应该为此使用会话。考虑使用视图模型,并在其中有一个 属性 可用于传递此数据。您始终可以根据需要通过视图数据字典将这些值作为附加数据传递给分部视图。
记住,HTTP 是无状态的。向其添加有状态行为时,请确保您出于正确的原因这样做。
正如其他人所提到的,我认为真正的解决办法是完全不这样做。我考虑了一下,虽然我有充分的理由使用会话,但由于 razor 标签只对初始页面加载有用,所以只用存储的会话值填充控制器中的视图模型更有意义。
然后您可以将具有当前会话值的视图模型传递给您的视图,并改为访问您的模型。然后你不必在你的视图中注入任何东西。
把它放在剃须刀页面的顶部
@using Microsoft.AspNetCore.Http;
然后你就可以像那样轻松访问会话变量
<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
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
有关 Asp.net 核心中会话的更多信息,请检查此 link Sessions in Asp.net Core
在 .net 核心 2.1 上测试
我正在尝试在 razor 视图中访问 .net core 2.0 项目的会话存储。在 .net 2.0 视图中是否有任何等效于 @Session["key"] 的东西?我还没有找到如何执行此操作的工作示例 - 我使用找到的方法遇到此错误:
An object reference is required for the non-static field, method, or propery HttpContext.Session
查看:
@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:
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?}");
});
}
你可以在视图中进行依赖注入,在 ASP.NET Core 2.0 :)
您应该将 IHttpContextAccessor
实现注入到您的视图中,并使用它从中获取 HttpContext
和 Session
对象。
@using Microsoft.AspNetCore.Http
@inject IHttpContextAccessor HttpContextAccessor
<script>
var isFiltered = '@HttpContextAccessor.HttpContext.Session.GetString("isFiltered")';
alert(isFiltered);
</script>
假设您在 Startup.cs
class 中有相关代码以启用会话,这应该可以工作。
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?}");
});
}
要在控制器中设置会话,您需要做同样的事情。将 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");
}
}
适当使用 Session。如果您试图传递一些特定于当前页面的数据,(例如:网格数据是否被过滤,这对当前请求非常特定),您不应该为此使用会话。考虑使用视图模型,并在其中有一个 属性 可用于传递此数据。您始终可以根据需要通过视图数据字典将这些值作为附加数据传递给分部视图。
记住,HTTP 是无状态的。向其添加有状态行为时,请确保您出于正确的原因这样做。
正如其他人所提到的,我认为真正的解决办法是完全不这样做。我考虑了一下,虽然我有充分的理由使用会话,但由于 razor 标签只对初始页面加载有用,所以只用存储的会话值填充控制器中的视图模型更有意义。
然后您可以将具有当前会话值的视图模型传递给您的视图,并改为访问您的模型。然后你不必在你的视图中注入任何东西。
把它放在剃须刀页面的顶部
@using Microsoft.AspNetCore.Http;
然后你就可以像那样轻松访问会话变量
<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
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
有关 Asp.net 核心中会话的更多信息,请检查此 link Sessions in Asp.net Core
在 .net 核心 2.1 上测试