Reputation: 370
I am currently developing an API in .Net Core 2.1 with a client application in Vue 2 with Nuxt, and I have problems saving an object in session in ASP .Net. I have reviewed this and other links before asking this question, but nothing has been able to help me. It turns out that I've tried it with Postman and if it works, but I do not understand why it does not work with my application.
This is my Startup.cs
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
options.CheckConsentNeeded = context => false;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
// Add Database
// End Add Database
services.AddCors(options =>
{
options.AddPolicy("AllowSpecificOrigin", builder =>
builder.AllowAnyHeader()
.AllowAnyMethod()
.AllowAnyOrigin()
));
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
.AddDistributedMemoryCache();
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(1440);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseCookiePolicy();
app.UseCors("AllowSpecificOrigin");
app.UseSession();
app.UseMvc();
}
}
In my controller:
[Route("api/customer/[controller]")]
[ApiController]
public class ClientController : ControllerBase { ...
... Get and set Session Var
var model = HttpContext.Session.GetString("User")
And other controller
HttpContext.Session.SetString("User", "Hello World")
HttpContext changes id every time I make a request for ajax, but postman does not change the Id and that's why I can recover the cookie.
Upvotes: 2
Views: 934
Reputation: 239380
You likely need to set the withCredentials
flag when making your AJAX request. That shouldn't be required for same-site requests, but you mentioned CORS and didn't specify that it was same-site. With jQuery, that just means adding it to xhrFields
in your your AJAX options object:
$.ajax({
...
xhrFields: {
withCredentials: true
}
});
Other libraries may have a different methodology, but all should have some way of setting this flag on the XMLHttpRequest
object.
Upvotes: 4