zoukankan      html  css  js  c++  java
  • ASP.NET Core 3.1 跨域问题解决方式

    初次用net core 3.1 开发webapi接口时遇到跨域问题,花费了点时间从网上找的资料,但是有些不全,所以下面就粘贴上解决办法,已经测试过,没问题的。

    修改项目中的Startup类,添加红色字体标注的代码,注意这是ASP.NET Core 3.1 跨域解决办法

        public class Startup
        {
            public Startup(IConfiguration configuration)
            {
                Configuration = configuration;                
            }
    
            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("cors",
                        builder => builder.AllowAnyOrigin()
                        .AllowAnyHeader()
                        .AllowAnyMethod()
                    );
                });
    
                services.AddControllers();
    
                services.AddMvcService(); 
    
                //注册Swagger生成器
                services.AddSwaggerService();       
    }
    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime applicationLifetime) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } applicationLifetime.ApplicationStarted.Register(() => { //网站启动完成执行 }); applicationLifetime.ApplicationStopping.Register(() => { //网站停止过程中执行 }); applicationLifetime.ApplicationStopped.Register(() => { //网站停止完成执行 }); app.UseRouting(); //允许所有跨域,cors是在ConfigureServices方法中配置的跨域策略名称 //注意:UseCors必须放在UseRouting和UseEndpoints之间 app.UseCors("cors"); //使用静态文件 app.UseStaticFiles(); app.UseAuthorization(); app.UseEndpoints(endpoints => { //跨域需添加RequireCors方法,cors是在ConfigureServices方法中配置的跨域策略名称 endpoints.MapControllers().RequireCors("cors"); }); //调用中间件 app.UseSwaggerMiddleware();
    } }
  • 相关阅读:
    为什么java的接口的方法是public abstract修饰?为什么属性是public static final 修饰?
    java方法的重载
    java的自增和自减
    html和jsp页面中把文本框禁用,只能读不能写的方法
    JavaScript的数据类型有哪些?
    thinkPHP 框架 delete方法无法删除数据 【已解决】
    Linux shell 数组
    redis cpu占用过高100%,清理病毒事件
    Linux 批量杀掉进程
    记一次宝塔Linux面板磁盘占满,删除文件后空间没有减少的问题
  • 原文地址:https://www.cnblogs.com/li150dan/p/12762681.html
Copyright © 2011-2022 走看看