[英].net core 2.1 CORS api
我有一個 api 可以處理 ajax 后的請求。 當我調用它時,我收到了臭名昭著的 Cors 錯誤消息:
CORS 策略已阻止從源 '' 在 '' 訪問 XMLHttpRequest:請求的資源上不存在“Access-Control-Allow-Origin” header
沒問題。 I've done this before and their is plenty of resources out there (eg Enable CORS in ASP .NET Core 2.1 Web Api ) describing how to add a cors policy to the startup. 問題是我似乎無法讓它工作。
這是我的 Sarup.cs:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy(MyAllowSpecificOrigins,
builder =>
{
builder.WithOrigins("*").AllowAnyMethod().AllowAnyHeader().AllowAnyOrigin();
});
});
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>(options =>
{
// User settings
options.User.RequireUniqueEmail = true;
options.SignIn.RequireConfirmedEmail = true;
// Password settings
options.Password.RequireDigit = true;
options.Password.RequiredLength = 8;
options.Password.RequiredUniqueChars = 1;
options.Password.RequireLowercase = false;
options.Password.RequireNonAlphanumeric = true;
options.Password.RequireUppercase = false;
})
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
// Add application services.
services.AddTransient<IEmailSender, EmailSender>();
services.AddAntiforgery(o => o.SuppressXFrameOptionsHeader = true);
services.AddMvc(options =>
{
options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env,
RoleManager<IdentityRole> roleManager, IServiceProvider serviceProvider)
{
app.UseCors(MyAllowSpecificOrigins);
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
app.UseDatabaseErrorPage();
app.UseCors(MyAllowSpecificOrigins);
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseCors(MyAllowSpecificOrigins);
}
app.UseStaticFiles();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
//UserDbContextSeed.Seed(serviceProvider).Wait();
}//Configure
}
}
這是我的 controller 的路線屬性:
[Route("api/v23")]
這是我的方法簽名
[Route("[action]")]
[HttpPost]
[IgnoreAntiforgeryToken]
public IActionResult Post_Data(model v){......}
最后是我的 ajax 請求:
$.ajax({
type: 'POST',
url: 'Myserver/api/v23/Post_Data',
dataType: 'json',
contentType: "application/json", //
data: JSON.stringify(Param),
success: function (result) {
console.log(results);
},
error: function (request, status, error) {
console.log(error);
}
});
我嘗試將 [Enable CORS("__myAllowSpecificOrigins") 屬性添加到 controller,但這也不起作用。 這應該不難,我顯然遺漏了一些明顯的東西。
有什么建議嗎?
嘗試將 AddCors 的語法更改為:
services.AddCors(o => o.AddPolicy(AllowSpecificOrigins, builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
}));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.