How to Send Asp.Net Session Cookie from Angular in Request to get session value in Asp.net Core Web API
Loading
How to Send Asp.Net Session Cookie from Angular in Request to get session value in Asp.net Core Web API
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Tahir AnsariRank #366 · 6.8K reputationPosted Jul 25, 2023, 7:07 AM EDT
Please try below example
public void ConfigureServices(IServiceCollection services) { // Other services and configurations services.AddDistributedMemoryCache(); services.AddSession(options => { options.Cookie.Name = ".AspNetCore.Session"; options.IdleTimeout = TimeSpan.FromMinutes(30); // Set the session timeout as needed options.Cookie.HttpOnly = true; options.Cookie.IsEssential = true; // Required to avoid GDPR consent issues }); }import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; @Injectable() export class ApiService { private apiUrl = 'https://your-api-url.com'; // Replace with your ASP.NET Core Web API URL constructor(private http: HttpClient) {} // Function to get session value from the ASP.NET Core Web API getSessionValue() { // Get the ASP.NET session cookie from the browser const aspSessionCookie = document.cookie .split(';') .find((cookie) => cookie.trim().startsWith('.AspNetCore.Session=')); // Set the ASP.NET session cookie in the request headers const headers = new HttpHeaders({ 'Content-Type': 'application/json', Cookie: aspSessionCookie, }); // Send a GET request to the API to get the session value return this.http.get(`${this.apiUrl}/api/sessionValue`, { headers }); } }[ApiController] [Route("api/[controller]")] public class SessionController : ControllerBase { [HttpGet("sessionValue")] public IActionResult GetSessionValue() { // Retrieve the session value from ASP.NET Core session var sessionValue = HttpContext.Session.GetString("your-session-key"); return Ok(sessionValue); } }Tuhin PaulRank #7 · 71.9K reputationPosted Feb 4, 2024, 12:53 PM EST
While it's technically possible to send an ASP.Net session cookie from Angular to an ASP.Net Core Web API, it's strongly discouraged due to security concerns and limitations.
Limitations:
Recommended Alternatives:
Instead of relying on ASP.Net session cookies, consider these more secure and recommended approaches: