如何解决在ASP.NET核心MVC项目上启用CORS
当我最终了解我的问题是CORS阻止了我时,我需要将用户重定向到另一个页面,我试图弄清楚如何将CORS启用到我要重定向到的特定URL上而没有任何运气...也许有人可以发现我的错误?
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();
_scheduler.JobFactory = new AspnetCoreJobFactory(app.ApplicationServices);
app.UseSession();
app.UseStaticFiles();
app.UseCors(MyAllowSpecificOrigins);
app.UseAuthentication();
app.UseRouting();
app.UseAuthorization();
app.UseCookiePolicy();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",pattern: "{controller=Users}/{action=Dashboard}/{id?}");
});
}
public void ConfigureServices(IServiceCollection services)
{
FACEBOOK_APP_ID = _config.GetValue<string>("FACEBOOK_APP_ID");
FACEBOOK_APP_SECRET = _config.GetValue<string>("FACEBOOK_APP_SECRET");
services.AddHttpsRedirection(options =>
{
options.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect;
options.HttpsPort = 44300;
});
services.AddHttpClient();
services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins,builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
});
services.AddMvc();
services.AddIdentity<ApplicationUser,IdentityRole>(options => options.User.AllowedUserNameCharacters = null).AddEntityFrameworkStores<AppDbContext>();
services.AddControllersWithViews();
services.AddDbContextPool<AppDbContext>(options => options.UseSqlServer(_config.GetConnectionString("AutoLoverDbConnection"),x => x.MigrationsAssembly("AutoMatcherProjectAss")).UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking));
services.AddTransient<AppDbContext>();
services.AddSingleton<IHttpContextAccessor,HttpContextAccessor>();
services.AddSingleton<IActionContextAccessor,ActionContextAccessor>();
services.AddSingleton<ISessionManager,ClientSIdeSessionManager>();
services.AddHttpContextAccessor();
services.AddSession();
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => false;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddDistributedMemoryCache();
services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromMinutes(60);//You can set Time
options.Cookie.HttpOnly = true;
});
services.AddTransient<ISche,SchedulerImpl>();
services.AddTransient<IQueue,QueueImpl>();
services.AddTransient<SchedulerJob>();
services.AddTransient<IBotFactory,BotFactory>();
services.AddTransient<IJsonFactory,JsonFactory>();
services.AddTransient<ICredentialDb,CredentialDb>();
services.AddSingleton(provider => _scheduler);
services.AddAuthentication().AddFacebook(options =>
{
options.AppId = FACEBOOK_APP_ID;
options.AppSecret = FACEBOOK_APP_SECRET;
options.SaveTokens = true;
});
_scheduler.Clear();
}
控制器:
[HttpPost]
public async Task<IActionResult> AuthenticateInstagramAPI(Service service)
{
return new RedirectResult("https://www.instagram.com/");
}
错误:
从来源“ https:// localhost:44300”访问“ https://www.instagram.com/”(从“ https:// localhost:44300 / Actions / AuthenticateInstagramAPI”重定向)的XMLHttpRequest的访问已被阻止根据CORS政策:在飞行前响应中,Access-Control-Allow-Headers不允许使用请求标头字段x-requested-with。
编辑----------
客户端AJAX调用:
function AuthInstagram() {
var service = $('#userServicesDropDownAuth :selected').text()
$.ajax({
url: '/Actions/AuthenticateInstagramAPI',method: 'POST',data: service,dataType: 'json',success: function (data) {
console.log(data);
},error: function (error) {
//alert(error+"11");
}
})
}
解决方法
在startup.cs中。您将 app.UseCors(MyAllowSpecificOrigins);
放在app.UseStaticFiles();
和app.UseAuthentication();
之间
在doc中,Calls the UseCors extension method and specifies the _myAllowSpecificOrigins CORS policy. UseCors adds the CORS middleware. The call to UseCors must be placed after UseRouting,but before UseAuthorization. For more information,see Middleware order.
因此您可以像这样更改数据:
app.UseRouting();
app.UseCors(MyAllowSpecificOrigins);
app.UseAuthorization();
,
想通了。
会显示出是否向Controller动作发送了AJAX get请求,并尝试从该动作进行重定向,但该动作无效。 可能是AJAX添加了一些标头,还是AJAX调用没有通过中间件管道进行?不知道,如果有人知道我为什么要这样做的答案!
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。