【问题标题】:Access to XMLHttpRequest at 'http://localhost:25776/api/Upload' from origin 'http://localhost:4200' has been blocked by CORS policy从源“http://localhost:4200”访问“http://localhost:25776/api/Upload”的 XMLHttpRequest 已被 CORS 策略阻止
【发布时间】:2020-11-02 19:30:08
【问题描述】:

我在 http://localhost:4200 运行 angular spa 应用程序,在 http://localhost:25667 运行 .net core 3 应用程序。

当我的 Angular SPA 不断收到以下错误消息时。

Access to XMLHttpRequest at 'http://localhost:25776/api/Upload' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

即使我认为我的 CORS 配置正确。

这是我的startup.cs 文件。

public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddPolicy(
                    name: "CorsPolicy",
                     builder => builder.WithOrigins("http://localhost:4200/")
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                    .AllowCredentials()
                    .SetIsOriginAllowed((host) => true));
            });

            services.AddHttpContextAccessor();

            services.AddControllers().AddNewtonsoftJson();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseCors("CorsPolicy");

 

            app.UseAuthorization();


            app.UseDefaultFiles();
            app.UseStaticFiles(new StaticFileOptions()
            {
                FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @"Upload")),
                RequestPath = new PathString("/Upload")
            });

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.MapFallbackToController("Index", "Fallback");
            });
        }

这是我的控制器文件

using System.Collections.Generic;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using TestApp.API.Models;
using TestApp.API.Services;
namespace TestApp.API.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    [EnableCors("CorsPolicy")]
    public class UploadController : ControllerBase
    {
        // GET api/value
        [HttpGet]
        public IEnumerable<Upload> GetTempUploadData()
        {
            UploadServices uploadServices = new UploadServices();
            return uploadServices.GetTempUploadData();

        }
    }
}

我还安装了 Microsoft.AspNetCore.Cors nuget 包。

任何帮助将不胜感激。

提前谢谢你。

【问题讨论】:

  • 我检查了您的配置并且可以在本地访问它。请清除缓存并重试。或在此操作 GetTempUploadData 中添加方法 (Response.Headers.Add("Access-Control-Allow-Origin", "*"))。
  • 谢谢@Karney。为愚蠢的问题道歉,但我如何清除 Visual Studio 中的缓存?

标签: c# angular asp.net-core


【解决方案1】:

您需要在WithOrigins 中删除此/

services.AddCors(options =>
        {
            options.AddPolicy(
                name: "CorsPolicy",
                 builder => builder.WithOrigins("http://localhost:4200")
                .AllowAnyHeader()
                .AllowAnyMethod()
                .AllowCredentials()
                .SetIsOriginAllowed((host) => true));
        });

【讨论】:

  • 我删除了/,但仍然是同样的错误。看起来它完全忽略了 CORS 政策。也许我在控制器中添加了不必要的using
  • 我终于想通了。我的launchSettings.json 文件将anonymousAuthentication 设置为false;我更改为true,它开始工作,因为我在本地调试了项目。非常感谢您帮助我解决问题:)
  • 是的,我在不同的浏览器中测试了 angular 引用的 url。由于安全问题,它可能会被阻止。
【解决方案2】:

我正在发布我的解决方案,以防有人遇到类似问题。

问题在于我的 API 中的 launchSetting.json 文件。 我将anonymousAuthentication 设置为true,它解决了这个问题。它与 CORS 设置无关。

  "iisSettings": {
    "windowsAuthentication": true,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:25776/",
      "sslPort": 0
    }

【讨论】:

    猜你喜欢
    • 2019-10-31
    • 2020-01-26
    • 2019-11-17
    • 2020-07-09
    • 2023-03-27
    • 2020-02-11
    • 1970-01-01
    • 2020-10-12
    • 2021-12-26
    相关资源
    最近更新 更多