微服务Demo

第1章 1.3 API 服务 (webapi) 支持跨域访问CO

2018-10-11  本文已影响168人  elef

前后台分离架构

前后台分离.png

使用前后端完全分离的架构,首先遇到的问题肯定是跨域访问。前后端可能不在同个server上,即使前后端处在同个server上,由于前后端完全分离,前后端使用的端口号也可能是不一样的,所以必须解决跨域访问。

API服务(webapi)添加cors

dotnet add package Microsoft.AspNetCore.Cors

全局设置跨域CORS

Startup.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

namespace chapter1_webapi
{
    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.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            //添加跨域访问策略
            //注意这句好放在最后
            services.AddCors(options =>
            {
                options.AddPolicy("AllowAllOrigin",
                    builder => builder.WithOrigins("*"));
            });

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }
            
            //启用跨域策略
            app.UseCors("AllowAllOrigin");

            app.UseHttpsRedirection();
            app.UseMvc();
        }
    }
}

其实开启CORS就是在返回客户端的HTTP头中增加一个字段

Response.Headers.Add("Access-Control-Allow-Origin","*");
上一篇下一篇

猜你喜欢

热点阅读