.net core 的跨域

來源:互聯網
上載者:User

標籤:als   function   cep   顯示   exp   msu   oid   log   過程   

.net core 的跨域問題花了 我很長時間 接下來我簡單的描述下解決過程

首先我在前端用jquery的ajax去調用自己的本地介面大致如下

$.ajax({type:"POST",url:"http://localhost:11969/api/Users/login",dataType:"Json",data:{"username":"Majiko2018","password": "majiko123",},success:function(data){console.log("成功");console.log(data)},error:function(err){console.log("失敗");console.log(err);}});

 

期間在不同的瀏覽器中顯示都不一樣

首先在chorme 中顯示不出具體錯誤只是顯示POST https://localhost:11969/api/Users/login 0 ()也不說具體啥錯

於是我就在Edge中去調試,這個還正常點知道報錯 No ‘Access-Control-Allow-Origin

 

 

同樣我也在explorer中debug了顯示錯誤如下

 

 

一開始我認為會不會是在VScode中 React項目 裡寫ajax會有什麼問題

因為已經嘗試了網上很多關於.net Core跨域的問題都沒能解決而且一直報同一個錯期間當然也包括一些部署上的問題500,404 等等 簡直絕望到死

後邊我就嘗試著注釋之前的所有嘗試再試一遍

在ConfigureServices中添加跨網域作業

 

 services.AddCors(options =>

             options.AddPolicy("any",

          builder => builder.AllowAnyMethod().AllowAnyHeader().AllowAnyOrigin().AllowCredentials()));

 

然後在controller層頭部添加

 [EnableCors("any")]

問題竟然解決了。。。

我現在都有點暈 這個.NET CORE的路由什麼的我才剛剛接觸都沒有入門 我想是我對它瞭解的不深入導致的

 

首先是Startup層

 public void Configure(IApplicationBuilder app, IHostingEnvironment env)        
{ app.UseCors("AllowAll2");//這個是必須的,且中間加什麼都可以?? if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } //這個也是必須的 app.UseCors(builder => builder .AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader()); app.UseMvc();}

 

        public void ConfigureServices(IServiceCollection services)        {            //這個也是必須的            services.AddCors(options =>            options.AddPolicy("any",         builder => builder.AllowAnyMethod().AllowAnyHeader().AllowAnyOrigin().AllowCredentials()));            services.AddMvc();        }

然後到Controller層

在namespace之下添加 [Route("api/Users")](再添加了前面兩個後,這個是非必須的)

 

這幾天我會仔細看一下這方面的東西系統的總結一遍~

 

.net core 的跨域

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.