无法访问会话asp.net核心

Jei*_*dez 6 c# asp.net session session-state asp.net-core

嗨,请帮助我尝试在asp.net核心测试会话但是当我设置会话并从其他控制器获取它似乎是null

继承我的创业公司

public class Startup
{

    public IConfigurationRoot Configuration { get; }
    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();
        Configuration = builder.Build();
    }


    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        // Add framework services.
        services.AddMvc().AddJsonOptions(options => {
            options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
        });

        // Adds a default in-memory implementation of IDistributedCache.
        services.AddDistributedMemoryCache();

        services.AddSession(options =>
        {
            // Set a short timeout for easy testing.
            options.IdleTimeout = TimeSpan.FromSeconds(600);
            options.CookieHttpOnly = true;
        });


        services.AddSingleton<IConfiguration>(Configuration);
        services.AddSingleton<Microsoft.AspNetCore.Http.IHttpContextAccessor, Microsoft.AspNetCore.Http.HttpContextAccessor>();
        services.AddTransient<IApiHelper, ApiHelper>();



    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        app.UseSession();
        app.UseDeveloperExceptionPage();
        if (env.IsDevelopment())
        {
            app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions {
                HotModuleReplacement = true,
                ReactHotModuleReplacement = true
            });
        }

        //var connectionString = Configuration.GetSection("ConnectionStrings").GetSection("ClientConnection").Value;


        app.UseStaticFiles();
        loggerFactory.AddConsole();


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

    public static void Main(string[] args) {
        var host = new WebHostBuilder()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseIISIntegration()
            .UseKestrel()
            .UseStartup<Startup>()
            .Build();

        host.Run();
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我如何设置会话

public class HomeController : Controller
{
    public IActionResult Index()
    {

        HttpContext.Session.SetString("Test", "Ben Rules!");

        return View();
    }

    public IActionResult Error()
    {
        return View();
    }
}
Run Code Online (Sandbox Code Playgroud)

在这里我再次获取会话的示例代码,但它似乎是null

    [HttpGet("[action]")]
    public IEnumerable<JobDescription> GetJobDefinitions()
    {
        //this is always null
        var xd = HttpContext.Session.GetString("Test");


        var x = _apiHelper.SendRequest<Boolean>($"api/JobRequest/GetJobRequest",null);
        var returnValue = new List<JobDescription>();
        returnValue = jobDescriptionManager.GetJobDescriptions();
        return returnValue;


    }
Run Code Online (Sandbox Code Playgroud)

谢谢您的帮助

nam*_*nam 2

为此VS2017,请遵循有关 ASP.NET Core 中的会话和应用程序状态的 MSDN 官方文章。您可以在我创建的以下示例中测试您的场景。注意:虽然下面的代码看起来很长,但事实上,您只需对从默认 ASP.NET Core 模板创建的默认应用程序进行一些细微的更改。只需按照以下步骤操作:

  1. 使用默认模板创建 ASP.NET Core MVC 应用程序 VS2017

  2. 修改默认Home controller如下图

  3. 确保该Startup.cs文件具有与会话相关的条目,如Startup.cs 下面的文件所示

  4. 运行应用程序并单击Home顶部栏上的链接。这将存储如下所示的会话值(Nam Wam2017current date

  5. 单击About顶部栏上的链接。您会注意到会话值已传递到About控制器。但我知道这不是你的问题,因为这只是测试将会话值传递给same控制器​​上的另一个操作。因此,要回答您的问题,请按照以下 3 个步骤操作。

  6. 创建另一个控制器AnotherController- 如下所示 - 使用新操作和文件夹内的 Test()视图Test.cshtmlViews\Test

  7. 在链接后_Layout.cshtml添加另一个链接,如下所示<li><a asp-area="" asp-controller="Another" asp-action="Test">Test View</a></li><li>...Contact...</li>

  8. 再次运行应用程序,然后首先单击Home顶部栏上的链接。然后单击Test顶部栏上的链接。您将注意到会话值已从 传递HomControllerAnotherController并已成功显示在Test视图上。

家庭控制器

using System;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;

namespace MyProject.Controllers
{
    public class HomeController : Controller
    {
        const string SessionKeyName = "_Name";
        const string SessionKeyFY = "_FY";
        const string SessionKeyDate = "_Date";

        public IActionResult Index()
        {
            HttpContext.Session.SetString(SessionKeyName, "Nam Wam");
            HttpContext.Session.SetInt32(SessionKeyFY , 2017);
            // Requires you add the Set extension method mentioned in the SessionExtensions static class.
            HttpContext.Session.Set<DateTime>(SessionKeyDate, DateTime.Now);

            return View();
        }

        public IActionResult About()
        {
            ViewBag.Name = HttpContext.Session.GetString(SessionKeyName);
            ViewBag.FY = HttpContext.Session.GetInt32(SessionKeyFY);
            ViewBag.Date = HttpContext.Session.Get<DateTime>(SessionKeyDate);

            ViewData["Message"] = "Session State In Asp.Net Core 1.1";

            return View();
        }

        public IActionResult Contact()
        {
            ViewData["Message"] = "Contact Details";

            return View();
        }

        public IActionResult Error()
        {
            return View();
        }

    }

    public static class SessionExtensions
    {
        public static void Set<T>(this ISession session, string key, T value)
        {
            session.SetString(key, JsonConvert.SerializeObject(value));
        }

        public static T Get<T>(this ISession session, string key)
        {
            var value = session.GetString(key);
            return value == null ? default(T) : JsonConvert.DeserializeObject<T>(value);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

About.cshtml [显示same控制器中的会话变量值]

@{
    ViewData["Title"] = "ASP.Net Core !!";
}
<h2>@ViewData["Title"].</h2>
<h3>@ViewData["Message"]</h3>


<table class="table table-responsive">
    <tr>
        <th>Name</th>
        <th>Fiscal Year</th>
    </tr>
    <tr>
        <td>@ViewBag.Name</td>
        <td>@ViewBag.FY</td>
    </tr>
</table>

<label>Date : @(ViewBag.Date.ToString("dd/MM/yyyy") != "01/01/0001" ? ViewBag.Date.ToString("dd/MM/yyyy") : "")</label>
Run Code Online (Sandbox Code Playgroud)

AnotherController [与 HomeController 不同的控制器]:

using System;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;

public class AnotherController : Controller
{
    const string SessionKeyName = "_Name";
    const string SessionKeyFY = "_FY";
    const string SessionKeyDate = "_Date";

    // GET: /<controller>/
    public IActionResult Test()
    {
        ViewBag.Name = HttpContext.Session.GetString(SessionKeyName);
        ViewBag.FY = HttpContext.Session.GetInt32(SessionKeyFY);
        ViewBag.Date = HttpContext.Session.Get<DateTime>(SessionKeyDate);

        ViewData["Message"] = "Session State passed to different controller";
        return View();
    }
}
Run Code Online (Sandbox Code Playgroud)

Test.cshtml:[显示从主控制器传递到Another控制器的会话变量值]

@{
    ViewData["Title"] = "View sent from AnotherController";
}
<h2>@ViewData["Title"].</h2>
<h3>@ViewData["Message"]</h3>


<table class="table table-responsive">
    <tr>
        <th>Test-Name</th>
        <th>Test-FY</th>
    </tr>
    <tr>
        <td>@ViewBag.Name</td>
        <td>@ViewBag.FY</td>
    </tr>
</table>

<label>Date : @(ViewBag.Date.ToString("dd/MM/yyyy") != "01/01/0001" ? ViewBag.Date.ToString("dd/MM/yyyy") : "")</label>
Run Code Online (Sandbox Code Playgroud)

_Layout.cshtml

....
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li><a asp-area="" asp-controller="Home" asp-action="Index">Home</a></li>
                    <li><a asp-area="" asp-controller="Home" asp-action="About">About</a></li>
                    <li><a asp-area="" asp-controller="Home" asp-action="Contact">Contact</a></li>
                    <li><a asp-area="" asp-controller="Another" asp-action="Test">Test View</a></li>
                </ul>
            </div>
....
Run Code Online (Sandbox Code Playgroud)

Startup.cs:[确保包含一些与会话相关的条目。当您在 VS2017 中创建 ASP.NET Core MVC 应用程序时,这些条目很可能已经存在。但请确保。]

....
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    //In-Memory
    services.AddDistributedMemoryCache();
    services.AddSession(options => {
        options.IdleTimeout = TimeSpan.FromMinutes(1);//Session Timeout.
    });              
    // Add framework services.
    services.AddMvc();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseBrowserLink();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }

    app.UseStaticFiles();

    app.UseSession();

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