【问题标题】:Asp.net Core Mvc Jquery client signalr and web api core 3.1 signalr with domain publish带有域发布的 Asp.net Core Mvc Jquery 客户端信号器和 web api 核心 3.1 信号器
【发布时间】:2021-05-17 05:10:49
【问题描述】:

以下代码 Jquery 和 asp.net core webapi 在domin 中不起作用,它抛出 signalr websockets 失败,从附件中会发现错误,但在本地工作正常。

Jquery Signalr 客户端代码和 Asp.net Core Web API:-

if (window.jQuery) {
    var _url = window.location.hostname == 'localhost' ? _local.replace('https', 'wss') : _ip_domain.replace('https', 'wss')
    var connection = new signalR.HubConnectionBuilder().withUrl(_ip_domain,
        {
            skipNegotiation: true,
            useDefaultPath: false,
            transport: signalR.HttpTransportType.WebSockets,//WebSockets
        }).configureLogging(signalR.LogLevel.Information).build();

    connection.on("ReceiveMessage", function (json) {
       console.log('msg received');
    });
    connection.on("ConnectionId", function (conid) {
        console.log('ConnectionId :' + conid);
    });
    async function start() {
        try {
            connection.start().then(function () {
                console.log("SignalR Connected.");
            });
        } catch (err) {
            console.log(err);
            setTimeout(start, 5000);
        }
    };
    connection.onclose(start);
    start();
}

Asp.Net Core 启动:-

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddHsts(options =>
        {
            options.Preload = true;
            options.IncludeSubDomains = true;
            options.MaxAge = TimeSpan.FromDays(60);
        });
        services.AddHttpsRedirection(options =>
            {
                options.RedirectStatusCode = (int)HttpStatusCode.PermanentRedirect;
                options.HttpsPort = 443;
            });

       
        services.AddSignalR();
        services.AddControllers();
        services.AddRouting(c => { c.LowercaseUrls = true; });

        services.AddSwaggerGen(swagger =>
        {
            swagger.SwaggerDoc("v1", new OpenApiInfo
            {
                Title = "IOT Core API",
                Version = "v1.1",
                Description = "API to unerstand request and response schema."                    
            });
        });
        services.AddControllers();
        services.AddDistributedMemoryCache();
        services.AddSession(options =>
        {
            options.Cookie.Name = "test";
            options.IdleTimeout = TimeSpan.FromMinutes(10);
            options.Cookie.HttpOnly = true;
            options.Cookie.IsEssential = true;
        });

        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
        services.AddMvcCore().AddApiExplorer();
        services.AddCors(options =>
        {
            options.AddPolicy(_cors, builder =>
            {
                builder/*.WithOrigins("https://ip_address/api/", "https://localhost:44340/", https://mywebsite.com/")*/
                .AllowAnyHeader()
                .AllowAnyMethod()
                .SetIsOriginAllowed(isOriginAllowed: _ => true)
                .AllowCredentials();
            });
        });
    }
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        app.UseHttpsRedirection();
        app.UseRouting();
        app.UseSession();
        app.UseAuthorization();
        app.UseAuthentication();
        app.UseWebSockets();
        app.UseCors(_cors);
        app.UseStaticFiles();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapHub<MotorHub>("/signalr", c =>
            {
                c.Transports = HttpTransportType.WebSockets;
            });
            endpoints.MapControllers().RequireCors(_cors);
        });
        app.UseSwagger();
        app.UseSwaggerUI(c =>
        {               
            string swaggerJsonBasePath = string.IsNullOrWhiteSpace(c.RoutePrefix) ? "." : "..";
            c.SwaggerEndpoint($"{swaggerJsonBasePath}/swagger/v1/swagger.json", "Version 1.1");
            c.SwaggerEndpoint($"{swaggerJsonBasePath}/swagger/v2/swagger.json", "Version 1.2");
        });
    

【问题讨论】:

  • 您似乎限制客户端仅使用WebSockets 作为传输,如果您尝试使用其他传输或让 SignalR 自动选择最佳传输方式,它可以连接到集线器吗?
  • 如果我使用自动选择,信号器会抛出协商错误,
  • 知道了,谢谢兄弟的建议......!

标签: asp.net signalr signalr-hub signalr.client asp.net-core-signalr


【解决方案1】:

Juery Signalr 客户端代码:-

1.如果你在iis服务器上发布,请在服务器管理器中启用websocket -> 添加角色 -> websockets协议并安装它。

2.new signalR.HubConnectionBuilder().withUrl(_domain,{skipNegotiate : true, transport : signalr.HttpTransport.WebSockets }).configureLogging(signalR.LogLevel.Information).build(); //应该删除所有限制传输,在信号器中它将自动选择最佳传输协议。

    var _ip_domain = "https://ipaddress:port/api/signalr";//ip addresss
    var _domain = "https://www.mywebsite.com/api/signalr";//web api url core 3.1, in api 
                                                         url should mention the "api/"

    var _local = "https://localhost:44393/signalr";

    console.clear();
    "use strict";
    if (window.jQuery) {
        var _url = window.location.hostname == 'localhost' ? _local : _domain
        var connection = new signalR.HubConnectionBuilder().withUrl(_domain)
            .configureLogging(signalR.LogLevel.Information).build();

        connection.on("ReceiveMessage", function (json) {
            console.log('message recieved');
        });
        connection.on("ConnectionId", function (conid) {
            console.log('ConnectionId :' + conid);
        });
        async function start() {
            try {
                connection.start().then(function () {
                    console.log("SignalR Connected.");
                });
            } catch (err) {
                console.log(err);
                setTimeout(start, 5000);
            }
        };
        connection.onclose(start);
        start();
    }

Asp.Net Core 3.1 Web API:-

API 应该映射 Signalr 路径并启用 Cors Origins...!

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }
    public IConfiguration Configuration { get; }
    private readonly string _cors = "AllowAllPolicy";
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddHsts(options =>
        {
            options.Preload = true;
            options.IncludeSubDomains = true;
            options.MaxAge = TimeSpan.FromDays(60);
        });
        services.AddHttpsRedirection(options =>
        {
            options.RedirectStatusCode = (int)HttpStatusCode.PermanentRedirect;
            options.HttpsPort = 443;
        });            
        services.AddControllers();
        services.AddRouting(c => { c.LowercaseUrls = true; });
        services.AddSwaggerGen(swagger =>
        {
            swagger.SwaggerDoc("v1", new OpenApiInfo
            {
                Title = "IOT Core API",
                Version = "v1.1",
                Description = "API to unerstand request and response schema."
            });
        });
        services.AddControllers();
        services.AddDistributedMemoryCache();
        services.AddSession(options =>
        {
            options.Cookie.Name = ".session";
            options.IdleTimeout = TimeSpan.FromMinutes(10);
            options.Cookie.HttpOnly = true;
            options.Cookie.IsEssential = true;
        });

        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
        services.AddMvcCore().AddApiExplorer();
        services.AddCors(options =>
        {
            options.AddPolicy(_cors, builder =>
            {
                builder.AllowAnyHeader()
                .AllowAnyMethod()
                .SetIsOriginAllowed(isOriginAllowed: _ => true)
                .AllowCredentials();
            });
        });
        services.AddSignalR();

    }
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseHsts();
        }
        app.UseHttpsRedirection();
        app.UseRouting();
        app.UseSession();
        app.UseAuthorization();
        app.UseAuthentication();
        app.UseWebSockets();
        app.UseCors(_cors);//enable cors
        app.UseStaticFiles();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapHub<SignalrHub>("/signalr");//signalr path
            endpoints.MapControllers();
        });
        app.UseSwagger();
        app.UseSwaggerUI(c =>
        {
            c.DocumentTitle = "API";
            string swaggerJsonBasePath = string.IsNullOrWhiteSpace(c.RoutePrefix) ? "." : "..";
            c.SwaggerEndpoint($"{swaggerJsonBasePath}/swagger/v1/swagger.json", "Version 1.1");
            c.SwaggerEndpoint($"{swaggerJsonBasePath}/swagger/v2/swagger.json", "Version 1.2");
        });
    }

信号集线器类

public class SignalrHub : Hub
{
    public override Task OnConnectedAsync()
    {
        Console.WriteLine("--> Connection Opened: " + Context.ConnectionId);
        Clients.Client(Context.ConnectionId).SendAsync("ConnectionId", Context.ConnectionId);
        return base.OnConnectedAsync();
    }
}

在你的控制器类 ex:valuescontroller

Should Initialize the hub context ;
private readonly IHubContext<MotorHub> hubContext;
 public ApiController(IHubContext<MotorHub> hubContext)
    {          
        this.hubContext = hubContext;            
    }
 Inside the Method you send the response to client, Paste the following lines : 
 await hubContext.Clients.All.SendAsync("ReceiveMessage", your_result);//if the result is json or any format...!

【讨论】:

    猜你喜欢
    • 2021-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多