【发布时间】: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