简体   繁体   中英

SignalR & Cross-Domain on AzureWebsite

I am trying to use SignalR on an AzureWebsites app and I'm stuck on a cross-domain issue.

Starting from this tutorial, everything works fine when run locally or when run on azurewebsites: https://docs.microsoft.com/en-us/aspnet/core/tutorials/signalr?view=aspnetcore-3.1&tabs=visual-studio

No changes to the tutorial code, all as is.

If I move the client to a different domain than the SignalR server app it no longer works.

I'm researching the issue but any pointers would be very appreciated.

What you need to do is firstly configure your SignalR application like this:

public void ConfigureServices(IServiceCollection services)
{
   services.AddCors(cfg =>
           {
                cfg.AddDefaultPolicy(policy =>
                {
                     policy.WithOrigins(Configuration.GetSection("AuthServer:DomainBaseUrl").Get<string[]>())
                     .AllowAnyHeader()
                     .AllowAnyMethod()
                     .AllowCredentials()
                     .SetIsOriginAllowed((_) => true)
                     .SetIsOriginAllowedToAllowWildcardSubdomains();
                });
           });
    services.AddSignalR(options =>
           {
                options.ClientTimeoutInterval = TimeSpan.FromHours(1);
                options.EnableDetailedErrors = true;
                options.HandshakeTimeout = TimeSpan.FromMinutes(10);
                options.KeepAliveInterval = TimeSpan.FromMinutes(5);
           });
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
      {
       // Code removed for brevity
       app.UseCors();

           app.UseEndpoints(endpoints =>
           {
                endpoints.MapControllers();
           });
}

NOTE: The line below

policy.WithOrigins(Configuration.GetSection("AuthServer:DomainBaseUrl").Get<string[]>())

is used to get the list of domains (array of domains) to allow for CORS from the config file and is.


And in your Client Application do this as well, hoping your client app is an ASP.NET Core MVC app too.

    public void ConfigureServices(IServiceCollection services)
{
   services.AddCors(cfg =>
           {
                cfg.AddDefaultPolicy(policy => {
                     policy.AllowAnyHeader();
                     policy.AllowAnyMethod();
                     policy.AllowAnyOrigin();
                     policy.WithMethods();
                });
           });
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
      {
       // Code removed for brevity
       app.UseCors();

           app.UseEndpoints(endpoints =>
           {
                endpoints.MapControllers();
           });
}

I hope this helps your situation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM