• 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();
    } }
  • 相关阅读:
    物理层和数据链路层
    Python :Dive Into Python 中文版 读后感_第五章__类与对象
    关于路由器的2种接法
    关于设计模式的一些理解和感悟
    C# 字符串加密
    Sql server 查询锁表和接锁表
    关于中文参数编码的一些文章推荐
    写与悟
    http 返回的状态码以及含义
    js 操作<input type="hidden" runnat="server" id="month">服务器控件
  • 原文地址:https://www.cnblogs.com/li150dan/p/12762681.html
Copyright © 2020-2023  润新知