![](/img/trans.png)
[英]How can I control the HTTP response headers added to my ASP.NET core web application when hosted in Azure app service?
[英]Call to my rest service from Angular app hosted in Asp.net core web server blocked by CORS policy
I have a Angular App that is hosted in Asp.net core web server, though this Angular app i am calling another Rest api service for getting some data but my call to external Rest Service api is blocked by CORS policy.
我在瀏覽器中遇到的錯誤是 -
和我的 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();
}
}
}
我已通過此鏈接在 Internet 上閱讀了有關如何解決此錯誤的信息How to enable CORS in ASP.net Core WebAPI但在我的情況下沒有成功。 請不要介意我是 web 開發的新手,並且在 CORS 政策錯誤上我已經卡了好幾天了。 請幫助我如何解決這個錯誤。 我還必須在我的外部 Rest api 服務上啟用 CORS。 謝謝!
CORS 是服務器端“問題”,而不是客戶端。 所以,我想,你不應該嘗試在你的客戶端上修復它(即,Angular,即使它托管在 X 服務器類型上)。 這就是為什么,我認為,您的 ASP.net 修復程序不起作用。 嘗試在客戶端修復 CORS 雖然有時可能,但大多數時候會導致錯誤或只是服務器忽略/阻止請求。
最簡單的方法是在服務器端配置 CORS 。 您已指定您正在訪問外部 REST API 。 因此,您必須深入挖掘並忘記客戶端修復。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.