[英]how to enable CORS in MVC .Net 5?
我在前端(javascript)有一個簡單的操作,它返回一些 JSON。這是代碼示例,
function DiacritizeText() {
var text = $("#Paragraph").val()
var api_key = "Api_Key";
var i;
var settings = {
"async": true,
"crossDomain": true,
"url": "https://farasa.qcri.org/webapi/segmentation/",
"method": "POST",
"headers": { "content-type": "application/json", "cache-control": "no-cache", },
"processData": false,
"data": "{\"text\":" + "\"" + text + "\", \"api_key\":" + "\"" + api_key + "\"}",
}
$.ajax(settings).done(function (response) {
console.log(response);
$("#Paragraph").text(JSON.parse(response).text);
});
}
當我執行這個 function 時,我得到了這些錯誤
Access to XMLHttpRequest at 'https://farasa.qcri.org/webapi/segmentation/' from origin https://localhost:44377' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
POST https://farasa.qcri.org/webapi/segmentation/ net::ERR_FAILED 400
我搜索了一些資源,其中大部分提供了處理應該在 API 完成,但這是不可能的,因為 API 不在我們的網絡中我必須嘗試從我這邊啟用腳趾 CORS
第一次嘗試是在 Startup 中添加 CORS
public class Startup
{
readonly string allowSpecificOrigins = "_allowSpecificOrigins";
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
{
builder.WithOrigins("https://farasa.qcri.org/")
.AllowAnyMethod()
.AllowAnyHeader();
}));
var ConnectionString = Configuration.GetConnectionString("EducationSystemDBContextConnection");
services.AddDbContext<EducationSystemDBContext>(options => options.UseSqlServer(ConnectionString));
var mapperConfig = new MapperConfiguration(mc =>
{
mc.AddProfile(new MappingProfile());
});
IMapper mapper = mapperConfig.CreateMapper();
services.AddSingleton(mapper);
//services.AddAutoMapper(typeof(Startup));
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie("Cookies", options =>
{
options.LoginPath = "/User/Login";
options.LogoutPath = "/User/Logout";
options.AccessDeniedPath = "/User/AccessDenied";
options.ReturnUrlParameter = "ReturnUrl";
});
services.AddControllersWithViews();
services.AddRazorPages();
}
// 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.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
//app.UseMvcWithDefaultRoute();
app.UseRouting();
app.UseCors("MyPolicy");
app.UseCookiePolicy(new CookiePolicyOptions()
{
MinimumSameSitePolicy = SameSiteMode.Strict
});
app.UseAuthentication();
app.UseAuthorization();
//app.MapRazorPages();
//app.MapDefaultControllerRoute();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
}
}
第二次嘗試,因為我在 ASP.Net Framework 中遇到了同樣的問題,我通過在 web.config 中添加來修復它我認為它可能 go 在.Net 核心中以相同的方式所以我在核心 MVC web 中添加了一個 web.config應用程序然后添加如下
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, OPTIONS" />
</customHeaders>
</httpProtocol>
</system.webServer>
那么,如何從我的核心 MVC web 應用程序處理 CORS?
public static void Register(HttpConfiguration config)
{
var corsAttribute = new EnableCorsAttribute("http://example.com", "*", "*");
config.EnableCors(corsAttrribute);
}
或者
HttpContext.Response.AppendHeader("Access-Control-Allow-Origin", "*");
或者您可以將其添加到 wor web.config 文件中:
<system.webServer>
<httpProtocol>
<customHeaders>
<clear />
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
如果要為 web api 啟用 CORS,則需要將其添加到 web Api 項目的 global.asax 文件夾中。
protected void Application_BeginRequest()
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.