question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

ASP.net Core MVC + REST server

See original GitHub issue

Describe your question

I’m trying to do a server REST and MQTT with ASP.net Core MVC for working with Unity3D. The REST server is working fine. I’m facing that issue when trying to connect to the server with WebSocket: QTTnet.Exceptions.MqttCommunicationException: Unable to connect to the remote server —> System.Net.WebSockets.WebSocketException: Unable to connect to the remote server

I tried for one week to make it work but I’m running out of ideas. I would be grateful if you guys can tell me what did I missed.

Versions: Microsoft.AspDotNetCore.App 3.1.2 Microsoft.NETCore.App 3.1.0 Microsoft.AspNetCore.Mvc.NewtonsoftJson 3.1.3 MQTTnet 3.0.11 MQTTnet.AspNetCore 3.0.11

The client connection part:

            var id = SystemInfo.deviceUniqueIdentifier;
            var factory = new MqttFactory();
            this.mqttClient = factory.CreateMqttClient();
            
            // WebSocket 
            var options = new MqttClientOptionsBuilder()
                    .WithClientId(id)
                    .WithWebSocketServer("ws://127.0.0.1:5000/mqtt")
                    .WithKeepAlivePeriod(TimeSpan.FromHours(24))
                    .WithKeepAliveSendInterval(TimeSpan.FromSeconds(5))
                    .WithCleanSession()
                    .Build();

            mqttClient.UseDisconnectedHandler(async e => {
                Debug.Log("### DISCONNECTED FROM SERVER ###");
                await Task.Delay(TimeSpan.FromSeconds(5));

                try {
                    await mqttClient.ConnectAsync(options, CancellationToken.None); // Since 3.0.5 with CancellationToken
                } catch (Exception ex) {
                    Debug.Log("### RECONNECTING FAILED ###");
                    Debug.Log(ex);
                }
            });

            try {
                await mqttClient.ConnectAsync(options, CancellationToken.None); // Since 3.0.5 with CancellationToken
            } catch (Exception e) {
                Debug.Log(e);
            }

The server Programm class:

public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
            //CreateHostBuilder(args).Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder => {
            webBuilder.UseStartup<Startup>();
        });

The server Configure Service:

public void ConfigureServices(IServiceCollection services)
        {
            // requires using Microsoft.Extensions.Options
            services.Configure<DatabaseSettings>(
                Configuration.GetSection(nameof(DatabaseSettings)));

            services.AddSingleton<IDatabaseSettings>(sp =>
                sp.GetRequiredService<IOptions<DatabaseSettings>>().Value);

            // Add Services
            services.AddSingleton<Service>();

            // Add Controllers
            services.AddControllers().AddNewtonsoftJson(options => options.UseMemberCasing());

            // MQTT
            services.AddSingleton<MqttService>();
            services.AddHostedMqttServerWithServices(options => {
                var s = options.ServiceProvider.GetRequiredService<MqttService>();
                s.ConfigureMqttServerOptions(options);
            });
            services.AddMqttWebSocketServerAdapter();
            services.AddMqttConnectionHandler();
        }

The server Configure

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment()) {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

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

            // MQTT
            _ = app.UseMqttEndpoint();
            app.UseMqttServer(server => app.ApplicationServices.GetRequiredService<MqttService>().ConfigureMqttServer(server));
        }

The server MQTT service witout all the implemented interfaces

public class MqttService : IMqttServerClientConnectedHandler, IMqttServerClientDisconnectedHandler, IMqttServerApplicationMessageInterceptor, IMqttServerConnectionValidator, IMqttServerStartedHandler
    {
        IMqttServer mqtt;

        public void ConfigureMqttServerOptions(AspNetMqttServerOptionsBuilder options)
        {
            options.WithConnectionValidator(this);
            options.WithApplicationMessageInterceptor(this);
        }

        public void ConfigureMqttServer(IMqttServer mqtt)
        {
            this.mqtt = mqtt;
            mqtt.ClientConnectedHandler = this;
            mqtt.ClientDisconnectedHandler = this;
        }

Thanks in advance !

edit: changed the versions to 3.0.11

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:5

github_iconTop GitHub Comments

1reaction
VallatMacommented, Jun 22, 2020

Thanks for all your answers 😃 Because of some time pressure, I made it work by changing from WebSocket to TCP.

So here my working setup:

Startup.cs ConfigureServices

            services.AddSingleton<MqttService>();
            services.AddHostedMqttServerWithServices(options => {
                var s = options.ServiceProvider.GetRequiredService<MqttService>();
                s.ConfigureMqttServerOptions(options);
            });
            services.AddConnections();
            services.AddMqttConnectionHandler();

Startup.cs Configure

            app.UseHttpsRedirection();
            app.UseRouting();
            app.UseAuthorization();
            app.UseEndpoints(endpoints => {
                endpoints.MapControllers();
                endpoints.MapMqtt("/mqtt");
            });
            app.UseMqttServer(server => app.ApplicationServices.GetRequiredService<MqttService>().ConfigureMqttServer(server));

Program.cs

public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
        .ConfigureWebHostDefaults(webBuilder => {
            webBuilder.ConfigureKestrel(serverOptions => {
                serverOptions.ListenAnyIP(1883, l => l.UseMqtt()); 
                serverOptions.ListenAnyIP(5000, l => l.UseHttps()); 
            }).UseStartup<Startup>();
        });
0reactions
SeppPennercommented, Jun 19, 2020

@JimmyPun610’s solution should work, as far as I can see from the examples 😃

Read more comments on GitHub >

github_iconTop Results From Across the Web

Tutorial: Create a web API with ASP.NET Core
Learn how to build a web API with ASP.NET Core.
Read more >
An awesome guide on how to build RESTful APIs with ASP ...
In this article, I'll show you how to write a well structured RESTful API for an “almost” real world scenario, using the ASP.NET...
Read more >
How to Build CRUD REST APIs with ASP.NET Core 3.1 ...
Follow these steps to create an ASP.NET Core application in Visual Studio 2019: Step 1: Go to File > New, and then select...
Read more >
How To Build a RESTful API with ASP.NET Core
First, open File -> New-> Project in Visual Studio: Select ASP.NET Core Web Application, give a name to the project and the solution ......
Read more >
Building an ASP.NET Web API with ASP.NET Core
In this article, Toptal Freelance ASP.NET Developer Damir Imangulov shows how to build a robust RESTful API using ASP.NET, EF Core, AutoMapper, and...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found