【问题标题】:CORS issue asp.net core web api. No 'Access-Control-Allow-Origin' header is present [closed]CORS 问题 asp.net core web api。不存在“Access-Control-Allow-Origin”标头[关闭]
【发布时间】:2020-05-18 01:04:28
【问题描述】:

我正在使用 asp net core 2.1,并且我有一个具有以下方法的帐户控制器:

    [HttpPost("login")]
    public async Task<object> Login([FromBody] IdentityUserForLoginDto userForLogin)
    {...}
    [HttpPost("register")]
    public async Task<object> Register([FromBody] IdentityClientForRegistrationDto userForRegistration)
    {...}

当我通过登录方法获取数据时,一切正常,用户正常登录,但是当我尝试注册新用户时,出现 CORS 问题:

CORS 策略已阻止从源“http://localhost:3001”获取“http://localhost:53531/api/account/register”的访问权限:请求的资源上不存在“Access-Control-Allow-Origin”标头。如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。

和:

POST http://localhost:53531/api/account/registernet::ERR_FAILED

在我的后端,我尝试了启用 CORS 的所有可能组合,现在我有了这个:

配置服务:

        services.AddCors(options => options.AddPolicy("ApiCorsPolicy", builder =>
        {
            builder
                .WithOrigins("http://localhost:3000", "http://localhost:3001")
                .AllowAnyHeader().AllowCredentials()
                .AllowAnyMethod();
        }));

配置

app.UseCors("ApiCorsPolicy");

客户端数据获取:

fetch(`http://localhost:53531/api/account/register`, {          
        method: 'POST',        
        headers: { 'Content-Type': 'application/json'},   

        body: JSON.stringify(values)


            })
    .then(handleResponse)
    .then(user => {

        localStorage.setItem('currentUser', JSON.stringify(user));
        currentUserSubject.next(user);

        return user;
    });

它们都放置在 Add/UseMvc 之前。 我已经尝试过 AllowAnyOrigin、[EnableCors] 等……但总是一样的。 我想指出,我也尝试过从客户端禁用 cors,但在这种情况下,我得到 text/plain 媒体类型,我明确想要 application/json

另外,当我在邮递员中提出同样的要求时,一切都很好..

有人知道如何解决这个问题吗?

【问题讨论】:

  • 能否分享调用注册端点的客户端代码?
  • 我已经编辑了原始帖子并添加了该部分
  • 我注意到您正在使用 fetch 进行 API 调用。 github.com/github/fetch 您可以尝试在此处提到的选项中添加credentials: 'include' github.github.io/fetch
  • 我做了,还是一样.. :/

标签: asp.net-core post cors asp.net-core-webapi


【解决方案1】:

我解决了这个问题。问题出在发送到服务器的数据中。它不是服务器预期的格式

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-30
    • 2016-05-13
    • 2017-12-11
    • 2021-10-20
    • 2018-03-04
    • 2016-10-30
    • 1970-01-01
    • 2017-04-15
    相关资源
    最近更新 更多