.net core实现前后端彻底分离

问题的关键在跨域

1.我们在services里面 添加跨域内容如下:

public void ConfigureServices(IServiceCollection services)
        {
            //这个AddOcelot方法是Ocelot包给IServiceCollection扩展的方法
            services.AddOcelot(configuration).AddConsul();
            #region CORS
            services.AddCors(c =>
            {
                //↓↓↓↓↓↓↓注意正式环境不要使用这种全开放的处理↓↓↓↓↓↓↓↓↓↓
                c.AddPolicy("AllRequests", policy =>
                {
                    policy
                    .AllowAnyOrigin()//允许任何源
                    .AllowAnyMethod()//允许任何方式
                    .AllowAnyHeader()//允许任何头
                    .AllowCredentials();//允许cookie
                });
                //↑↑↑↑↑↑↑注意正式环境不要使用这种全开放的处理↑↑↑↑↑↑↑↑↑↑


                //一般采用这种方法
                c.AddPolicy("LimitRequests", policy =>
                {
                    policy
                    .WithOrigins("http://localhost:8020", "http://blog.core.xxx.com", "")//支持多个域名端口
                    .WithMethods("GET", "POST", "PUT", "DELETE")//请求方法添加到策略
                    .WithHeaders("authorization");//标头添加到策略
                });

            });
            #endregion
        }

2.在中间件中添加跨域内容

 // 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();
            }
            #region 跨域相关
            app.UseCors("AllRequests");
            #endregion
            //app.Run(async (context) =>
            //{
            //    await context.Response.WriteAsync("Hello World!");
            //});
            app.UseOcelot().Wait();
        }

注意如果项目没有用ocelot 直接是请求webapi  我们上述内容写在webapi的startup文件中

如果项目使用了ocelot 那么我们的上述内容只需要写在ocelot项目中

3.跨域请求 get没什么问题 但是post要注意:

post请求传递参数要有如下代码:

一个完整的例子:

<html>

    <head>
        <meta charset="utf-8" />
        <title>请求</title>
        <script type="text/javascript" src="js/jquery-1.8.3.js"></script>
        <script type="text/javascript">
            $.ajax({
                type: "post",
                url: "https://www.xxx.net/xxxService/Category/AddCategory",
                data: JSON.stringify({
                    "CategoryName": "类别",
                    "Code": 4
                }),
                contentType:"application/json",
                                                   
                success: function(data) {
                    console.log(data);
                },
                error: function() {
                    console.log("请求错误")
                }
            });
        </script>
    </head>

    <body>

    </body>

</html>

done!

原文地址:https://www.cnblogs.com/wholeworld/p/9648072.html