razor view .net core 2中的访问会话变量 [英] Access session variable in razor view .net core 2

查看:89
本文介绍了razor view .net core 2中的访问会话变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试以剃刀视图访问.net core 2.0项目的会话存储.在.net 2.0视图中,@ Session ["key"]是否有等效项?我尚未找到如何执行此操作的有效示例-我使用发现的方法遇到此错误:

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:

非静态字段,方法或属性HttpContext.Session需要对象引用

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:

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中的视图中进行依赖项注入:)

You can do dependency injection in views, in ASP.NET Core 2.0 :)

您应该将IHttpContextAccessor实现注入到您的视图中,并使用它从中获取HttpContextSession对象.

You should inject IHttpContextAccessor implementation to your view and use it to get the HttpContext and Session object from that.

@using Microsoft.AspNetCore.Http
@inject IHttpContextAccessor HttpContextAccessor
<script>
   var isFiltered = '@HttpContextAccessor.HttpContext.Session.GetString("isFiltered")';
   alert(isFiltered);
</script>

如果您在Startup.cs类中具有相关代码以启用会话,这应该可以工作.

This should work assuming you have the relevant code in the Startup.cs class to enable session.

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注入您的控制器并使用

To set session in a controller, you do the same thing. Inject the IHttpContextAccessor to your controller and use that

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.

请记住, Http是无状态的.在向其中添加有状态行为时,请确保您出于正确的原因在执行此操作.

Remember, Http is stateless. When adding stateful behavior to that, make sure you are doing it for the right reason.

这篇关于razor view .net core 2中的访问会话变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆