我正在http://localhost:4200
上运行angular spa应用程序,并在http://localhost:25667
上运行.net core 3应用程序。
当我的角度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软件包。
任何帮助将不胜感激。
谢谢。
答案 0 :(得分:1)
您需要在/
中删除此WithOrigins
。
services.AddCors(options =>
{
options.AddPolicy(
name: "CorsPolicy",
builder => builder.WithOrigins("http://localhost:4200")
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials()
.SetIsOriginAllowed((host) => true));
});
答案 1 :(得分:0)
我正在发布我的解决方案,以防有人遇到类似问题。
问题与我的API中的launchSetting.json
文件有关。
我将anonymousAuthentication
设置为true
,它解决了这个问题。与CORS设置无关。
"iisSettings": {
"windowsAuthentication": true,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:25776/",
"sslPort": 0
}