1. 程式人生 > >asp.net core 使用SignalR跨域請求出現的坑

asp.net core 使用SignalR跨域請求出現的坑

前段時間因為工作需要,認識到了SignalR,這個東西本身挺好用,但是在處理跨域問題上是遭遇了很大的坑。

我在本地通過localhost連線的時候毫無問題,但是當我在前端使用IP來連線我的後臺,則會出現連線失敗的問題。查閱了很多,詢問公司內的大牛之後,找到一個正確解決方案,特記錄如下:

首先,在Strartup.cs檔案下處理跨域問題

        public const string CorsName = "SignalRCors";

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddSignalR();
            services.AddCors(options =>
            {
                options.AddPolicy(CorsName,
                    policy => policy.AllowAnyOrigin()
                                    .AllowAnyHeader()
                                    .AllowAnyMethod()
                                    .AllowCredentials());
            });
            services.AddMvc((opt) =>
            {
                opt.Filters.Add(new CorsAuthorizationFilterFactory(CorsName));
            }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            //services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }

        // 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.UseExceptionHandler("/Error");
                app.UseHsts();
            }
            app.UseCors(CorsName);

之後右鍵你的專案進入屬性-除錯,記下你的http埠號以及htts的埠號

然後找到applicationhost.config檔案,一般路徑是專案資料夾\.vs\config\applicationhost.config。找到如下程式碼

<sites>
      <site name="WebSite1" id="1" serverAutoStart="true">
        <application path="/">
          <virtualDirectory path="/" physicalPath="%IIS_SITES_HOME%\WebSite1" />
        </application>
        <bindings>
          <binding protocol="http" bindingInformation=":8080:localhost" />
        </bindings>
      </site>
      <site name="signalrTotest" id="2">
        <application path="/" applicationPool="Clr4IntegratedAppPool">
          <virtualDirectory path="/" physicalPath="C:\Users\JC.YX\Desktop\signalrTotest\signalrTotest" />
        </application>
        <bindings>
                    <binding protocol="https" bindingInformation=":44331:localhost" />
                    <binding protocol="http" bindingInformation=":35000:localhost" />
        </bindings>
      </site>

可以看到有https和http的埠設定,以及允許localhost連線。這時我們只需要在它們下面新增自己的IP地址就可以了。新增之後的程式碼如下

<sites>
      <site name="WebSite1" id="1" serverAutoStart="true">
        <application path="/">
          <virtualDirectory path="/" physicalPath="%IIS_SITES_HOME%\WebSite1" />
        </application>
        <bindings>
          <binding protocol="http" bindingInformation=":8080:localhost" />
        </bindings>
      </site>
      <site name="signalrTotest" id="2">
        <application path="/" applicationPool="Clr4IntegratedAppPool">
          <virtualDirectory path="/" physicalPath="C:\Users\JC.YX\Desktop\signalrTotest\signalrTotest" />
        </application>
        <bindings>
                    <binding protocol="https" bindingInformation=":44331:localhost" />
                    <binding protocol="https" bindingInformation=":44331:192.168.0.104" />
                    <binding protocol="http" bindingInformation=":35000:localhost" />
                    <binding protocol="http" bindingInformation=":35000:192.168.0.104" />
        </bindings>
      </site>

這時,將你的前端程式碼修改為對應IP地址加埠號,啟動IIS服務,你可以盡情的和朋友在聊天室裡聊天了

var connection = new signalR.HubConnectionBuilder().withUrl("http://yourIP:35000/chatHub").build();

注意:如果你前端寫的是http協議,請在啟動IIS服務之後,將預設開啟的網址修改為http協議加對應的埠號。