会话变量在视图中

时间:2018-05-06 18:57:44

标签: c# asp.net-core

前段时间我创建了一些简单的会话登录。它是一个MVC应用程序,但如果我是正确的,使用.net框架4.6。我可以使用像

这样的东西
<h2>@Session["ID"]</h2>

来自会话变量的ID应该在h2标签中。但现在我尝试使用.net core 2.0构建相同的内容。

我的startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddDbContext<L2Context>(options =>
            options.UseSqlite("Data Source=test.db"));

    services.AddDistributedMemoryCache(); // Adds a default in-memory implementation of IDistributedCache
    services.AddSession(options => {
        options.IdleTimeout = TimeSpan.FromMinutes(30);
    });
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }

    app.UseStaticFiles();
    app.UseSession();

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}

控制器将数据保存到会话中:

[HttpPost]
public IActionResult Login(Users user)
{
    var optionsBuilder = new DbContextOptionsBuilder<L2Context>();
    optionsBuilder.UseSqlite("Data Source=test.db");

    using (L2Context db = new L2Context(optionsBuilder.Options))
    {
        var user = db.Users.Single(u => u.Login == user.Login && u.Password == user.Password);
        if (user != null)
        {
            HttpContext.Session.SetString("ID", user.ID.ToString());
            HttpContext.Session.SetString("Login", user.Login.ToString());
            return RedirectToAction(nameof(LoggedIn));
        }
        else
        {
            ModelState.AddModelError("", "Login or password is invalid");
        }
    }
    return View();
}

LoggedIn View:

@{
    ViewData["Title"] = "LoggedIn";
}

<h4> Hello @Session["Login"]</h4>

那么,我在这里有错误吗?我很难在上次使用时工作。

我明白了:

  

错误CS0103:当前上下文中不存在名称“会话”

3 个答案:

答案 0 :(得分:3)

在ASP.NET Core中,默认情况下,View无法访问Session对象的HttpContext属性。您可以通过在视图中导入Http命名空间来访问它:

//import the namespace to make the class available within the view
@using Microsoft.AspNetCore.Http

然后,您可以访问Session对象的HttpContext属性:

<h4> Hello @HttpContext.Session.GetString("Login")</h4>

答案 1 :(得分:1)

.NET Core 2.0和.NET 4.6之间存在一些差异。其中之一是在.NET Core 2.0中,您没有可用的Session属性。可以使用HttpContext Context属性来获取会话。

这应该有效:

@{
    ViewData["Title"] = "LoggedIn";
}

<h4> Hello @Context.Session["Login"]</h4>

答案 2 :(得分:1)

还有一种方法可以做到这一点。有了它,你不需要围绕会议进行麻瓜。 我要告诉你我是怎么做到的。

第1步 创建一个我们稍后将在我们的视图中使用的常量文件

using System;

namespace MyProject.CONSTANTS
{
    public static class Constants
    {
        public static String USER_ENTITY
        {
            get
            {
                return "USER_ENTITY";
            }
        }
    }
}

第2步 为相同的AppUser.cs

创建应用程序级别IAppUser和Interface
namespace MyProject.Configurations.Interface
{
    public interface IAppUser
    {
        UserDto UserEntity { get; }
    }
}

namespace MyProject.Configurations
{
    public class AppUser : IAppUser
    {
        private IHttpContextAccessor httpContextProvider;

        public AppUser(IHttpContextAccessor _httpContextProvider)
        {
            httpContextProvider = _httpContextProvider;
        }

        public UserDto UserEntity
        {
            get
            {
                return httpContextProvider.HttpContext.Session.Get<UserDto>(Constants.USER_ENTITY);
            }
        }
    }
}

第3步 现在,当您获取数据时,将其存储如下

HttpContext.Session.Set(Constants.USER_ENTITY, result); //here result is type of `UserDto.cs` class

我们上面做了什么

我们将Session存储在常量中,稍后我们将在视图中使用依赖注入。

第4步 我们有一个共享视图_viewImports.cshtml,其中包含所有依赖注入。

我们将在此视图中注入我们的IAppUser接口,现在可以访问所有视图。

_viewImports.cshtml中执行以下操作 -

@using MyProject
@using Microsoft.Extensions.Options;
@inject MyProject.Configurations.Interface.IAppUser AppUser  //AppUser is an aleas

现在,在任何视图中,您现在都可以使用IAppUser接口的属性,该接口通过AppUser.cs类解析。

假设UserDto.cs的属性为

public int ID {get;set;}

您可以将其用作 - @AppUser.UserEntity.ID

全部

相关问题