我只能在使用浏览器地址栏

时间:2016-10-06 12:24:31

标签: session asp.net-core-mvc

设定:

所以我有两个可视工作室实例正在运行。

1)后端:使用名为homeController的MVC控制器的MVC 6应用程序

2)前端:网站项目。 HTML。

我没有使用mvc中的传统视图构建它,而是使用MVC后端获取数据的独立HTML网页。 - 我喜欢将它们分开。

测试

所以我想在MVC 6中第一次使用会话,然后关注this guide

首先测试很顺利,因为我没有费心去编写html和ajax,我只是从地址栏中调用了mvc,如下所示:

http://localhost:55043/home/setsession

背后的代码是:

[HttpGet]
public string SetSession()
{
   string sessionId = "1";
   HttpContext.Session.SetString(sessionId, "myvalue");
   return sessionId;
}

然后:

http://localhost:55043/home/getsession?sessionId=1

背后的代码是:

[HttpGet]
public string GetSession(string sessionId)
{
   string value = HttpContext.Session.GetString(sessionId);
   return "session value is: " + value;
}

它正确地回报了我的价值。

问题:

但是当我用相同的方法编写网站及其calles时,它就不记得第二次调用中设置的值。

我的代码是这样的:

$.ajax({
    url: url + "/home/SetSession",
    type: 'GET',
    async: true,
    crossDomain: true,
    cache: true,
    success: function (data) {
        alert("finito - Sessionid: " + data);
        $.ajax({
            url: url + "/home/GetSession",
            data: {
                sessionId: data,
            },
            type: 'GET',
            async: true,
            crossDomain: true,
            cache: true,
            success: function (data) {
                alert(data);
            },
            error: function (x, t, m) {
                alert("failed");
            }
        });
    },
    error: function (x, t, m) {
        alert("failed);
    }
});

那么为什么它不适用于我的网站?有什么区别?

我的一些Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddMvc();
    services.AddCors();
    services.AddCaching();
    services.AddSession(options => {
        options.IdleTimeout = TimeSpan.FromMinutes(30);
        options.CookieName = ".BrunataBooking";
    });
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    app.UseIISPlatformHandler();

    app.UseStaticFiles();

    app.UseSession();

    app.UseCors(builder =>
    {
        builder.WithOrigins("*")
               .WithMethods("GET", "POST")
               .AllowAnyHeader();
    });

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

0 个答案:

没有答案