我在.net Web api中将一个请求的cookie值共享给另一个请求,如下所述,
第一个请求:-
[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";
}
第二个请求:-
[HttpGet]
[Route("api/MyAttendance/GetUser")]
public string GetUser()
{
HttpCookie cookie = HttpContext.Current.Request.Cookies["userAuth"];
var sessionId = cookie["sessionId"];
//some code
return sessionId;
}
当我访问第一个请求时,sessionID
将存储在httpcookie
中,以便我可以从第二个请求中获取此cookie值。我可以从.net网站成功完成此过程api(后端)和邮递员提供。但是,当我从angular(frontend)执行相同的处理时,第一个请求成功运行,但是第二个请求无法执行,由于无法访问cookie值,这给了我以下错误。
System.NullReferenceException:对象引用未设置为实例 一个对象。
来自有角项目(前端)的呼叫请求:-
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()));;
}
我对这个问题一无所知。有人可以解释一下如何解决吗?
答案 0 :(得分:1)
这很可能是CORS问题。您需要使用凭据选项的用户
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()));;
}