微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Asp.net Core Mvc Jquery 客户端信号器和带有域发布的 web api 核心 3.1 信号器

如何解决Asp.net Core Mvc Jquery 客户端信号器和带有域发布的 web api 核心 3.1 信号器

enter image description here

以下代码 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");
        });
    

解决方法

Juery Signalr 客户端代码:-

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

2.new signalR.HubConnectionBuilder().withUrl(_domain,{skipNegotiate : true,transport : signalr.HttpTransport.WebSockets }).configureLogging(signalR.LogLevel.Information).build(); //应该去掉所有的restrict传输,在signalr中它会自动选择最好的传输协议。

    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();
    }
}

在您的控制器类中,例如: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...!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。