Angular WithCredentials不适用于POST,PUT

时间:2018-05-02 09:02:20

标签: .net angular cors httpclient

我正在使用Angular网站:

•localhost / test上的.Net Framework服务器

•localhost上的客户端:4200

我的Cookie身份验证工作正常,我的GET请求工作正常。

   this.httpClient.get<Test>('dummyUrl', { withCredentials: true });

在我的服务器的web.config中,我有以下内容。

    <add name="Access-Control-Allow-Credentials" value="true"/>
    <add name="Access-Control-Allow-Origin" value="http://localhost:4200" />
    <add name="Access-Control-Allow-Methods" value="*" />

鉴于此设置,我希望同样适用于PUT和POST请求。

    this.httpClient.put('dummyUrl', this.payload, { withCredentials: true });

我从此获得了401 Unauthorized。

我的调查

我看到的请求方法是OPTIONS,它告诉我这在飞行前是失败的,而且这个问题与CORS而不是Angular有关。我一直无法解决我所缺少的问题。

我很感激任何指导。

3 个答案:

答案 0 :(得分:1)

请尝试以下代码。

import { RequestOptions, Headers } from '@angular/http';

let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers, withCredentials: true });

this.httpClient.put('dummyUrl', this.payload, options);

答案 1 :(得分:0)

即使在POST请求中使用{withCredentials: true},我也遇到了类似的问题。

在我的Spring Boot服务器的代码中(用于处理CORS),我将Access-Control-Allow-Origin标头设置为*。我将*更改为http://localhost:4200,从该位置开始提供Angular应用。

此后一切正常。希望这对某人有帮助。

答案 2 :(得分:0)

如果您在前端有角度的asp net core api中使用,则在web api中,启动设置(在configure方法下),

按照设置进行设置

        app.UseCors(options =>
        {
            options.SetIsOriginAllowed(origin => true);
            //options.AllowAnyOrigin();
            options.AllowAnyHeader();
            options.AllowAnyMethod();
            options.AllowCredentials();   <-- This one is important
        });

它应该可以工作。

相关问题