Rasindu De Alwis
Rasindu De Alwis

Reputation: 149

Can't retrieve C# cookies from angular

I am sharing a cookie value from one request to another in .net web api as mentioned bellow,

1st Request :-

[HttpGet]
[Route("api/MyAttendance/loginTask")]
public async Task<string> loginTask()
{    
    //some code

    DateTime now = DateTime.Now;

    HttpCookie cookie = new HttpCookie("userAuth");

    cookie["sessionId"] = sessionID;
    HttpContext.Current.Response.Cookies.Add(cookie);
    cookie.Expires = now.AddYears(50);    

    return "Successful";
}

2nd Request :-

        [HttpGet]
        [Route("api/MyAttendance/GetUser")]
        public string GetUser()
        {

            HttpCookie cookie = HttpContext.Current.Request.Cookies["userAuth"];
            var sessionId = cookie["sessionId"];

            //some code

            return sessionId;   
        }

When I access the 1st request, the sessionID will be stored in the httpcookie so that I can get this cookie value from the 2nd request.I can do this process successfully from the .net web api(backend)and from postman.but when I do the same process from the angular(frontend),1st request works successfully but 2nd request will not execute it gives me following error because cookie value cannot be accessed.

System.NullReferenceException: Object reference not set to an instance of an object.

Calling Requests from the angular project(Frontend) :-

 getAuthentication(): Observable<any[]> {
    return this._http.get('http://localhost:2073/api/MyAttendance/loginTask').pipe(
      map((response: Response) => <any[]>response.json()));
  }

  getUserData(): Observable<any> {
    return this._http.get("http://localhost:2073/api/MyAttendance/GetUser").pipe(
      map((response: Response) => <any[]>response.json()));;
  }

I have no idea about this problem.Can someone explain me how to resolve this?

Upvotes: 1

Views: 950

Answers (1)

Athanasios Kataras
Athanasios Kataras

Reputation: 26372

This is most probably a CORS issue. You need to user with credentials option

https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials

 let options = new RequestOptions({ headers: headers, withCredentials: true });


  getAuthentication(): Observable<any[]> {
    return this._http.get('http://localhost:2073/api/MyAttendance/loginTask', options).pipe(
      map((response: Response) => <any[]>response.json()));
  }

  getUserData(): Observable<any> {
    return this._http.get("http://localhost:2073/api/MyAttendance/GetUser", options).pipe(
      map((response: Response) => <any[]>response.json()));;
  }

Upvotes: 1

Related Questions