我有一个网络服务ASP.NetWebAPI2和Angular6客户端。
[RoutePrefix("api/auth")]
public class AuthController : ApiController
{
[HttpPost]
public HttpResponseMessage LogInUser(LoginData loginData)
{
// .. check password ...
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1, // ticket version
loginData.UserName, // authenticated username
DateTime.Now, // issueDate
DateTime.Now.AddMinutes(60), // expiryDate
true, // true to persist across browser sessions
String.Empty, // can be used to store additional user data !!! Cannot be null!!!
FormsAuthentication.FormsCookiePath); // the path for the cookie
// Encrypt the ticket using the machine key
string encryptedTicket = FormsAuthentication.Encrypt(ticket);
CookieHeaderValue cookie = new CookieHeaderValue(FormsAuthentication.FormsCookieName, encryptedTicket);
HttpResponseMessage respMessage = new HttpResponseMessage();
respMessage.Headers.AddCookies(new CookieHeaderValue[] { cookie});
return respMessage;
}
}
在服务器端启用COR,在客户端我总是设置“withCredentials”:
@Injectable()
export class IcaHttpInterceptor implements HttpInterceptor {
constructor() {
}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
request = request.clone({
withCredentials: true
});
console.log("outgoing request", request);
return next.handle(request);
}
}
因此,如果我使用HttpClient发布到“localhost/api/auth”,我会在响应头中得到cookie,下一次发布到“api/auth”中的另一个方法时,cookie也会被发送,但现在当我将请求发送到另一个路径(例如“api/users”)时,cookie不会被发送。。
问题是为什么?