【发布时间】:2020-09-11 20:07:41
【问题描述】:
我有一个托管在 Asp.net 核心 Web 服务器中的 Angular 应用程序,虽然这个 Angular 应用程序我正在调用另一个 Rest api 服务来获取一些数据,但我对外部 Rest Service api 的调用被 CORS 策略阻止。
我在浏览器中遇到的错误是 -
和我的 Asp.net 服务器应用程序 Startup.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace WebclientServer
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit
https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
});
services.AddMvc();
}
// 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.UseRouting();
//app.UseEndpoints(endpoints =>
//{
// endpoints.MapGet("/", async context =>
// {
// await context.Response.WriteAsync("Hello World!");
// });
//});
app.UseCors("CorsPolicy");
app.Use(async (context, next) => {
await next();
if (context.Response.StatusCode == 404 &&
!Path.HasExtension(context.Request.Path.Value) &&
!context.Request.Path.Value.StartsWith("/api/"))
{
context.Request.Path = "/index.html";
await next();
}
});
//app.UseMvcWithDefaultRoute();
app.UseDefaultFiles();
app.UseStaticFiles();
}
}
}
我已通过此链接How to enable CORS in ASP.net Core WebAPI 阅读了有关如何在 Internet 上解决此错误的信息,但在我的情况下没有成功。请不要介意我是 Web 开发的新手,并且在 CORS 策略错误上我已经卡了好几天了。请帮助我如何解决这个错误。我还必须在我的 External Rest api 服务上启用 CORS。 谢谢!
【问题讨论】:
标签: c# asp.net angular cors cross-domain-policy