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();
    } }
  • 相关阅读:
    OC与JavaScript的交互
    号码运商判断
    iOS 适配https(AFNetworking3.0为例)
    UIlabel的字体自适应属性
    iOS10遇到有推送的Demo真机报错的解决
    UIView的setNeedsDisplay和setNeedsLayout
    ubuntu---设置路径时,profile和bashrc区别
    python---类的定义和使用
    ubuntu---鼠标变成空心十字架
    python--- 遍历一个图片文件夹 并 输出到txt文件
  • 原文地址:https://www.cnblogs.com/li150dan/p/12762681.html
Copyright © 2011-2022 走看看