.net core 下的跨域设置
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了.net core 下的跨域设置,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2322字,纯文字阅读大概需要4分钟。
内容图文
1.CORS中间件处理跨源请求。以下代码为具有指定源的整个应用程序启用CORS:
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } // 跨域配置 string[] strs = { "https://localhost:44384" }; app.UseCors(builder => builder.WithOrigins(strs)); app.UseHttpsRedirection(); app.UseMvc(); }
2.跨域策略的定义
public void ConfigureServices(IServiceCollection services) { services.AddHttpClient(); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); //跨域设置 services.AddCors(Options => { //①允许某一域名的请求 Options.AddPolicy("allow1", builder => { builder.WithOrigins("https://localhost:44384"); }); //②允许所有域名的请求 Options.AddPolicy("allow2", builder => { builder.AllowAnyOrigin(); }); //③允许某域名的请求,且限制该请求的类型 Options.AddPolicy("allow3", builder => { builder.WithOrigins("https://localhost:44384").WithMethods("POST","HEAD"); //builder.WithOrigins("https://localhost:44384").AllowAnyMethod();//允许所有的请求的类型 }); //④允许某域名的请求,带请求头部信息 Options.AddPolicy("allow4", builder => { builder.WithOrigins("https://localhost:44384").WithHeaders("accept", "content-type", "origin", "x-custom-header"); //builder.WithOrigins("https://localhost:44384").AllowAnyHeader();// //builder.WithOrigins("https://localhost:44384").WithExposedHeaders("x-custom-header");//指定的说明文头信息 }); //⑤允许某域名的请求,预检时间多久可以被缓存 Options.AddPolicy("allow5", builder => { builder.WithOrigins("https://localhost:44384").SetPreflightMaxAge(TimeSpan.FromSeconds(2520)); }); Options.AddPolicy("allow6", builder => { builder.WithOrigins("https://localhost:44384" ); }); }); }
开启其中一种策略
public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { // 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.UseCors( "allow5" ); app.UseHttpsRedirection(); app.UseMvc(); }
在mvc层中开启策略,在Controller、Action头部添加相应策略名称
[EnableCors("allow6")] [Route("api/[controller]")] [ApiController] publicclass ValuesController : ControllerBase { }
原文:https://www.cnblogs.com/-xyl/p/11137213.html
内容总结
以上是互联网集市为您收集整理的.net core 下的跨域设置全部内容,希望文章能够帮你解决.net core 下的跨域设置所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。