.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!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM