├── .gitignore ├── Extensions └── ServiceCollectionExtension.cs ├── Mqtt.Client.AspNetCore.csproj ├── Program.cs ├── Properties └── launchSettings.json ├── README.md ├── Services ├── ExtarnalService.cs ├── IMqttClientService.cs ├── MqttClientService.cs └── MqttClientServiceProvider.cs ├── Settings ├── AppSettingsProvider.cs ├── BrokerHostSettings.cs └── ClientSettings.cs ├── Startup.cs ├── appsettings.Development.json └── appsettings.json /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Aa][Rr][Mm]/ 27 | [Aa][Rr][Mm]64/ 28 | bld/ 29 | [Bb]in/ 30 | [Oo]bj/ 31 | [Ll]og/ 32 | [Ll]ogs/ 33 | 34 | # Visual Studio 2015/2017 cache/options directory 35 | .vs/ 36 | # Uncomment if you have tasks that create the project's static files in wwwroot 37 | #wwwroot/ 38 | 39 | # Visual Studio 2017 auto generated files 40 | Generated\ Files/ 41 | 42 | # MSTest test Results 43 | [Tt]est[Rr]esult*/ 44 | [Bb]uild[Ll]og.* 45 | 46 | # NUnit 47 | *.VisualState.xml 48 | TestResult.xml 49 | nunit-*.xml 50 | 51 | # Build Results of an ATL Project 52 | [Dd]ebugPS/ 53 | [Rr]eleasePS/ 54 | dlldata.c 55 | 56 | # Benchmark Results 57 | BenchmarkDotNet.Artifacts/ 58 | 59 | # .NET Core 60 | project.lock.json 61 | project.fragment.lock.json 62 | artifacts/ 63 | 64 | # StyleCop 65 | StyleCopReport.xml 66 | 67 | # Files built by Visual Studio 68 | *_i.c 69 | *_p.c 70 | *_h.h 71 | *.ilk 72 | *.meta 73 | *.obj 74 | *.iobj 75 | *.pch 76 | *.pdb 77 | *.ipdb 78 | *.pgc 79 | *.pgd 80 | *.rsp 81 | *.sbr 82 | *.tlb 83 | *.tli 84 | *.tlh 85 | *.tmp 86 | *.tmp_proj 87 | *_wpftmp.csproj 88 | *.log 89 | *.vspscc 90 | *.vssscc 91 | .builds 92 | *.pidb 93 | *.svclog 94 | *.scc 95 | 96 | # Chutzpah Test files 97 | _Chutzpah* 98 | 99 | # Visual C++ cache files 100 | ipch/ 101 | *.aps 102 | *.ncb 103 | *.opendb 104 | *.opensdf 105 | *.sdf 106 | *.cachefile 107 | *.VC.db 108 | *.VC.VC.opendb 109 | 110 | # Visual Studio profiler 111 | *.psess 112 | *.vsp 113 | *.vspx 114 | *.sap 115 | 116 | # Visual Studio Trace Files 117 | *.e2e 118 | 119 | # TFS 2012 Local Workspace 120 | $tf/ 121 | 122 | # Guidance Automation Toolkit 123 | *.gpState 124 | 125 | # ReSharper is a .NET coding add-in 126 | _ReSharper*/ 127 | *.[Rr]e[Ss]harper 128 | *.DotSettings.user 129 | 130 | # JustCode is a .NET coding add-in 131 | .JustCode 132 | 133 | # TeamCity is a build add-in 134 | _TeamCity* 135 | 136 | # DotCover is a Code Coverage Tool 137 | *.dotCover 138 | 139 | # AxoCover is a Code Coverage Tool 140 | .axoCover/* 141 | !.axoCover/settings.json 142 | 143 | # Visual Studio code coverage results 144 | *.coverage 145 | *.coveragexml 146 | 147 | # NCrunch 148 | _NCrunch_* 149 | .*crunch*.local.xml 150 | nCrunchTemp_* 151 | 152 | # MightyMoose 153 | *.mm.* 154 | AutoTest.Net/ 155 | 156 | # Web workbench (sass) 157 | .sass-cache/ 158 | 159 | # Installshield output folder 160 | [Ee]xpress/ 161 | 162 | # DocProject is a documentation generator add-in 163 | DocProject/buildhelp/ 164 | DocProject/Help/*.HxT 165 | DocProject/Help/*.HxC 166 | DocProject/Help/*.hhc 167 | DocProject/Help/*.hhk 168 | DocProject/Help/*.hhp 169 | DocProject/Help/Html2 170 | DocProject/Help/html 171 | 172 | # Click-Once directory 173 | publish/ 174 | 175 | # Publish Web Output 176 | *.[Pp]ublish.xml 177 | *.azurePubxml 178 | # Note: Comment the next line if you want to checkin your web deploy settings, 179 | # but database connection strings (with potential passwords) will be unencrypted 180 | *.pubxml 181 | *.publishproj 182 | 183 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 184 | # checkin your Azure Web App publish settings, but sensitive information contained 185 | # in these scripts will be unencrypted 186 | PublishScripts/ 187 | 188 | # NuGet Packages 189 | *.nupkg 190 | # NuGet Symbol Packages 191 | *.snupkg 192 | # The packages folder can be ignored because of Package Restore 193 | **/[Pp]ackages/* 194 | # except build/, which is used as an MSBuild target. 195 | !**/[Pp]ackages/build/ 196 | # Uncomment if necessary however generally it will be regenerated when needed 197 | #!**/[Pp]ackages/repositories.config 198 | # NuGet v3's project.json files produces more ignorable files 199 | *.nuget.props 200 | *.nuget.targets 201 | 202 | # Microsoft Azure Build Output 203 | csx/ 204 | *.build.csdef 205 | 206 | # Microsoft Azure Emulator 207 | ecf/ 208 | rcf/ 209 | 210 | # Windows Store app package directories and files 211 | AppPackages/ 212 | BundleArtifacts/ 213 | Package.StoreAssociation.xml 214 | _pkginfo.txt 215 | *.appx 216 | *.appxbundle 217 | *.appxupload 218 | 219 | # Visual Studio cache files 220 | # files ending in .cache can be ignored 221 | *.[Cc]ache 222 | # but keep track of directories ending in .cache 223 | !?*.[Cc]ache/ 224 | 225 | # Others 226 | ClientBin/ 227 | ~$* 228 | *~ 229 | *.dbmdl 230 | *.dbproj.schemaview 231 | *.jfm 232 | *.pfx 233 | *.publishsettings 234 | orleans.codegen.cs 235 | 236 | # Including strong name files can present a security risk 237 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 238 | #*.snk 239 | 240 | # Since there are multiple workflows, uncomment next line to ignore bower_components 241 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 242 | #bower_components/ 243 | 244 | # RIA/Silverlight projects 245 | Generated_Code/ 246 | 247 | # Backup & report files from converting an old project file 248 | # to a newer Visual Studio version. Backup files are not needed, 249 | # because we have git ;-) 250 | _UpgradeReport_Files/ 251 | Backup*/ 252 | UpgradeLog*.XML 253 | UpgradeLog*.htm 254 | ServiceFabricBackup/ 255 | *.rptproj.bak 256 | 257 | # SQL Server files 258 | *.mdf 259 | *.ldf 260 | *.ndf 261 | 262 | # Business Intelligence projects 263 | *.rdl.data 264 | *.bim.layout 265 | *.bim_*.settings 266 | *.rptproj.rsuser 267 | *- [Bb]ackup.rdl 268 | *- [Bb]ackup ([0-9]).rdl 269 | *- [Bb]ackup ([0-9][0-9]).rdl 270 | 271 | # Microsoft Fakes 272 | FakesAssemblies/ 273 | 274 | # GhostDoc plugin setting file 275 | *.GhostDoc.xml 276 | 277 | # Node.js Tools for Visual Studio 278 | .ntvs_analysis.dat 279 | node_modules/ 280 | 281 | # Visual Studio 6 build log 282 | *.plg 283 | 284 | # Visual Studio 6 workspace options file 285 | *.opt 286 | 287 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 288 | *.vbw 289 | 290 | # Visual Studio LightSwitch build output 291 | **/*.HTMLClient/GeneratedArtifacts 292 | **/*.DesktopClient/GeneratedArtifacts 293 | **/*.DesktopClient/ModelManifest.xml 294 | **/*.Server/GeneratedArtifacts 295 | **/*.Server/ModelManifest.xml 296 | _Pvt_Extensions 297 | 298 | # Paket dependency manager 299 | .paket/paket.exe 300 | paket-files/ 301 | 302 | # FAKE - F# Make 303 | .fake/ 304 | 305 | # CodeRush personal settings 306 | .cr/personal 307 | 308 | # Python Tools for Visual Studio (PTVS) 309 | __pycache__/ 310 | *.pyc 311 | 312 | # Cake - Uncomment if you are using it 313 | # tools/** 314 | # !tools/packages.config 315 | 316 | # Tabs Studio 317 | *.tss 318 | 319 | # Telerik's JustMock configuration file 320 | *.jmconfig 321 | 322 | # BizTalk build output 323 | *.btp.cs 324 | *.btm.cs 325 | *.odx.cs 326 | *.xsd.cs 327 | 328 | # OpenCover UI analysis results 329 | OpenCover/ 330 | 331 | # Azure Stream Analytics local run output 332 | ASALocalRun/ 333 | 334 | # MSBuild Binary and Structured Log 335 | *.binlog 336 | 337 | # NVidia Nsight GPU debugger configuration file 338 | *.nvuser 339 | 340 | # MFractors (Xamarin productivity tool) working folder 341 | .mfractor/ 342 | 343 | # Local History for Visual Studio 344 | .localhistory/ 345 | 346 | # BeatPulse healthcheck temp database 347 | healthchecksdb 348 | 349 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 350 | MigrationBackup/ 351 | 352 | # Ionide (cross platform F# VS Code tools) working folder 353 | .ionide/ 354 | 355 | 356 | # Windows executable file 357 | Program.exe 358 | 359 | # VS Code config 360 | .vscode/ 361 | 362 | # VS config 363 | .vs/ 364 | 365 | -------------------------------------------------------------------------------- /Extensions/ServiceCollectionExtension.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.DependencyInjection; 2 | using Microsoft.Extensions.Hosting; 3 | using Mqtt.Client.AspNetCore.Services; 4 | using Mqtt.Client.AspNetCore.Settings; 5 | using MQTTnet.Client; 6 | using System; 7 | 8 | namespace Mqtt.Client.AspNetCore.Extensions 9 | { 10 | public static class ServiceCollectionExtension 11 | { 12 | public static IServiceCollection AddMqttClientHostedService(this IServiceCollection services) 13 | { 14 | services.AddMqttClientServiceWithConfig(aspOptionBuilder => 15 | { 16 | var clientSettinigs = AppSettingsProvider.ClientSettings; 17 | var brokerHostSettings = AppSettingsProvider.BrokerHostSettings; 18 | 19 | aspOptionBuilder 20 | .WithCredentials(clientSettinigs.UserName, clientSettinigs.Password) 21 | .WithClientId(clientSettinigs.Id) 22 | .WithTcpServer(brokerHostSettings.Host, brokerHostSettings.Port); 23 | }); 24 | return services; 25 | } 26 | 27 | private static IServiceCollection AddMqttClientServiceWithConfig(this IServiceCollection services, Action configure) 28 | { 29 | services.AddSingleton(serviceProvider => 30 | { 31 | var optionBuilder = new MqttClientOptionsBuilder(); 32 | configure(optionBuilder); 33 | return optionBuilder.Build(); 34 | }); 35 | services.AddSingleton(); 36 | services.AddSingleton(serviceProvider => 37 | { 38 | return serviceProvider.GetService(); 39 | }); 40 | services.AddSingleton(serviceProvider => 41 | { 42 | var mqttClientService = serviceProvider.GetService(); 43 | var mqttClientServiceProvider = new MqttClientServiceProvider(mqttClientService); 44 | return mqttClientServiceProvider; 45 | }); 46 | return services; 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /Mqtt.Client.AspNetCore.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net6;net7 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.AspNetCore.Hosting; 6 | using Microsoft.Extensions.Configuration; 7 | using Microsoft.Extensions.Hosting; 8 | using Microsoft.Extensions.Logging; 9 | 10 | namespace Mqtt.Client.AspNetCore 11 | { 12 | public class Program 13 | { 14 | public static void Main(string[] args) 15 | { 16 | CreateHostBuilder(args).Build().Run(); 17 | } 18 | 19 | public static IHostBuilder CreateHostBuilder(string[] args) => 20 | Host.CreateDefaultBuilder(args) 21 | .ConfigureWebHostDefaults(webBuilder => 22 | { 23 | webBuilder.UseStartup(); 24 | }); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Properties/launchSettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "iisSettings": { 3 | "windowsAuthentication": false, 4 | "anonymousAuthentication": true, 5 | "iisExpress": { 6 | "applicationUrl": "http://localhost:44977", 7 | "sslPort": 44313 8 | } 9 | }, 10 | "profiles": { 11 | "IIS Express": { 12 | "commandName": "IISExpress", 13 | "launchBrowser": true, 14 | "environmentVariables": { 15 | "ASPNETCORE_ENVIRONMENT": "Development" 16 | } 17 | }, 18 | "Mqtt.Client.AspNetCore": { 19 | "commandName": "Project", 20 | "launchBrowser": true, 21 | "applicationUrl": "https://localhost:5001;http://localhost:5000", 22 | "environmentVariables": { 23 | "ASPNETCORE_ENVIRONMENT": "Development" 24 | } 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # MQTT Client ASP.NET Core 2 | 3 | This repository is an example of how to use [MQTTnet](https://github.com/chkr1011/MQTTnet) client in ASP.NET core web application with services. 4 | 5 | 6 | 7 | MQTT Client is running in `MqttClientService` by`IHostedService`, and it is a `singleton` service. 8 | 9 | To access `MqttClientService` from other external services inject `MQTTClientServiceProvider` in service constructor. 10 | 11 | Here is an example 12 | 13 | ```csharp 14 | public class ExtarnalService 15 | { 16 | private readonly IMqttClientService mqttClientService; 17 | public ExtarnalService(MqttClientServiceProvider provider) 18 | { 19 | mqttClientService = provider.MqttClientService; 20 | } 21 | } 22 | ``` 23 | 24 | 25 | 26 | **Configuration** 27 | 28 | Configure your MQTT settings in `appSettings.json` 29 | 30 | ```json 31 | "BrokerHostSettings": { 32 | "Host": "localhost", 33 | "Port": 1883 34 | }, 35 | 36 | "ClientSettings": { 37 | "Id": "5eb020f043ba8930506acbdd", 38 | "UserName": "rafiul", 39 | "Password": "12345678" 40 | }, 41 | ``` 42 | 43 | 44 | 45 | **Reconnecting** 46 | 47 | Reference Code:https://github.com/dotnet/MQTTnet/blob/master/Samples/Client/Client_Connection_Samples.cs 48 | The implemented code is in `MqttClientService.cs` 49 | 50 | 1. Reconnect_Using_Event 51 | 52 | ```c# 53 | public async Task HandleDisconnectedAsync(MqttClientDisconnectedEventArgs eventArgs) 54 | { 55 | 56 | if (e.ClientWasConnected) 57 | { 58 | // Use the current options as the new options. 59 | await mqttClient.ConnectAsync(mqttClient.Options); 60 | } 61 | } 62 | 63 | ``` 64 | 65 | "Reconnect_Using_Event" is not recommended, so the code is commented out ,the following code is recommended "Reconnect_Using_Time" 66 | 67 | 2. Reconnect_Using_Timer 68 | 69 | ```c# 70 | public async Task StartAsync(CancellationToken cancellationToken) 71 | { 72 | await mqttClient.ConnectAsync(options); 73 | /* 74 | * This sample shows how to reconnect when the connection was dropped. 75 | * This approach uses a custom Task/Thread which will monitor the connection status. 76 | * This is the recommended way but requires more custom code! 77 | */ 78 | _ = Task.Run( 79 | async () => 80 | { 81 | // // User proper cancellation and no while(true). 82 | while (true) 83 | { 84 | try 85 | { 86 | // This code will also do the very first connect! So no call to _ConnectAsync_ is required in the first place. 87 | if (!await mqttClient.TryPingAsync()) 88 | { 89 | await mqttClient.ConnectAsync(mqttClient.Options, CancellationToken.None); 90 | 91 | // Subscribe to topics when session is clean etc. 92 | _logger.LogInformation("The MQTT client is connected."); 93 | } 94 | } 95 | catch (Exception ex) 96 | { 97 | // Handle the exception properly (logging etc.). 98 | _logger.LogError(ex, "The MQTT client connection failed"); 99 | } 100 | finally 101 | { 102 | // Check the connection state every 5 seconds and perform a reconnect if required. 103 | await Task.Delay(TimeSpan.FromSeconds(5)); 104 | } 105 | } 106 | }); 107 | 108 | } 109 | ``` 110 | 111 | 112 | 113 | **Now do whatever you want to do with `MQTTClientService`!** -------------------------------------------------------------------------------- /Services/ExtarnalService.cs: -------------------------------------------------------------------------------- 1 | namespace Mqtt.Client.AspNetCore.Services 2 | { 3 | public class ExtarnalService 4 | { 5 | private readonly IMqttClientService mqttClientService; 6 | public ExtarnalService(MqttClientServiceProvider provider) 7 | { 8 | mqttClientService = provider.MqttClientService; 9 | } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Services/IMqttClientService.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Hosting; 2 | namespace Mqtt.Client.AspNetCore.Services 3 | { 4 | public interface IMqttClientService : IHostedService 5 | { 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /Services/MqttClientService.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Extensions.Logging; 2 | using MQTTnet; 3 | using MQTTnet.Client; 4 | using System; 5 | using System.Threading; 6 | using System.Threading.Tasks; 7 | 8 | namespace Mqtt.Client.AspNetCore.Services 9 | { 10 | public class MqttClientService : IMqttClientService 11 | { 12 | private readonly IMqttClient mqttClient; 13 | private readonly MqttClientOptions options; 14 | private readonly ILogger _logger; 15 | 16 | public MqttClientService(MqttClientOptions options, ILogger logger) 17 | { 18 | this.options = options; 19 | mqttClient = new MqttFactory().CreateMqttClient(); 20 | _logger = logger; 21 | ConfigureMqttClient(); 22 | } 23 | 24 | private void ConfigureMqttClient() 25 | { 26 | mqttClient.ConnectedAsync += HandleConnectedAsync; 27 | mqttClient.DisconnectedAsync += HandleDisconnectedAsync; 28 | mqttClient.ApplicationMessageReceivedAsync += HandleApplicationMessageReceivedAsync; 29 | } 30 | 31 | public Task HandleApplicationMessageReceivedAsync(MqttApplicationMessageReceivedEventArgs eventArgs) 32 | { 33 | throw new System.NotImplementedException(); 34 | } 35 | 36 | public async Task HandleConnectedAsync(MqttClientConnectedEventArgs eventArgs) 37 | { 38 | _logger.LogInformation("connected"); 39 | await mqttClient.SubscribeAsync("hello/world"); 40 | } 41 | 42 | public async Task HandleDisconnectedAsync(MqttClientDisconnectedEventArgs eventArgs) 43 | { 44 | 45 | _logger.LogInformation("HandleDisconnected"); 46 | #region Reconnect_Using_Event :https://github.com/dotnet/MQTTnet/blob/master/Samples/Client/Client_Connection_Samples.cs 47 | /* 48 | * This sample shows how to reconnect when the connection was dropped. 49 | * This approach uses one of the events from the client. 50 | * This approach has a risk of dead locks! Consider using the timer approach (see sample). 51 | * The following reconnection code "Reconnect_Using_Timer" is recommended 52 | */ 53 | //if (eventArgs.ClientWasConnected) 54 | //{ 55 | // // Use the current options as the new options. 56 | // await mqttClient.ConnectAsync(mqttClient.Options); 57 | //} 58 | #endregion 59 | await Task.CompletedTask; 60 | } 61 | 62 | public async Task StartAsync(CancellationToken cancellationToken) 63 | { 64 | await mqttClient.ConnectAsync(options); 65 | 66 | #region Reconnect_Using_Timer:https://github.com/dotnet/MQTTnet/blob/master/Samples/Client/Client_Connection_Samples.cs 67 | /* 68 | * This sample shows how to reconnect when the connection was dropped. 69 | * This approach uses a custom Task/Thread which will monitor the connection status. 70 | * This is the recommended way but requires more custom code! 71 | */ 72 | _ = Task.Run( 73 | async () => 74 | { 75 | // // User proper cancellation and no while(true). 76 | while (true) 77 | { 78 | try 79 | { 80 | // This code will also do the very first connect! So no call to _ConnectAsync_ is required in the first place. 81 | if (!await mqttClient.TryPingAsync()) 82 | { 83 | await mqttClient.ConnectAsync(mqttClient.Options, CancellationToken.None); 84 | 85 | // Subscribe to topics when session is clean etc. 86 | _logger.LogInformation("The MQTT client is connected."); 87 | } 88 | } 89 | catch (Exception ex) 90 | { 91 | // Handle the exception properly (logging etc.). 92 | _logger.LogError(ex, "The MQTT client connection failed"); 93 | } 94 | finally 95 | { 96 | // Check the connection state every 5 seconds and perform a reconnect if required. 97 | await Task.Delay(TimeSpan.FromSeconds(5)); 98 | } 99 | } 100 | }); 101 | #endregion 102 | 103 | } 104 | 105 | public async Task StopAsync(CancellationToken cancellationToken) 106 | { 107 | if (cancellationToken.IsCancellationRequested) 108 | { 109 | var disconnectOption = new MqttClientDisconnectOptions 110 | { 111 | Reason = MqttClientDisconnectReason.NormalDisconnection, 112 | ReasonString = "NormalDiconnection" 113 | }; 114 | await mqttClient.DisconnectAsync(disconnectOption, cancellationToken); 115 | } 116 | await mqttClient.DisconnectAsync(); 117 | } 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /Services/MqttClientServiceProvider.cs: -------------------------------------------------------------------------------- 1 | namespace Mqtt.Client.AspNetCore.Services 2 | { 3 | public class MqttClientServiceProvider 4 | { 5 | public readonly IMqttClientService MqttClientService; 6 | 7 | public MqttClientServiceProvider(IMqttClientService mqttClientService) 8 | { 9 | MqttClientService = mqttClientService; 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Settings/AppSettingsProvider.cs: -------------------------------------------------------------------------------- 1 | namespace Mqtt.Client.AspNetCore.Settings 2 | { 3 | public class AppSettingsProvider 4 | { 5 | public static BrokerHostSettings BrokerHostSettings; 6 | public static ClientSettings ClientSettings; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /Settings/BrokerHostSettings.cs: -------------------------------------------------------------------------------- 1 | namespace Mqtt.Client.AspNetCore.Settings 2 | { 3 | public class BrokerHostSettings 4 | { 5 | public string Host { set; get; } 6 | public int Port { set; get; } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /Settings/ClientSettings.cs: -------------------------------------------------------------------------------- 1 | namespace Mqtt.Client.AspNetCore.Settings 2 | { 3 | public class ClientSettings 4 | { 5 | public string Id { set; get; } 6 | public string UserName { set; get; } 7 | public string Password { set; get; } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /Startup.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.AspNetCore.Builder; 2 | using Microsoft.AspNetCore.Hosting; 3 | using Microsoft.AspNetCore.Http; 4 | using Microsoft.Extensions.Configuration; 5 | using Microsoft.Extensions.DependencyInjection; 6 | using Microsoft.Extensions.Hosting; 7 | using Mqtt.Client.AspNetCore.Extensions; 8 | using Mqtt.Client.AspNetCore.Services; 9 | using Mqtt.Client.AspNetCore.Settings; 10 | 11 | namespace Mqtt.Client.AspNetCore 12 | { 13 | public class Startup 14 | { 15 | // This method gets called by the runtime. Use this method to add services to the container. 16 | // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 17 | 18 | 19 | public Startup(IConfiguration configuration) 20 | { 21 | Configuration = configuration; 22 | MapConfiguration(); 23 | } 24 | 25 | public IConfiguration Configuration; 26 | 27 | private void MapConfiguration() 28 | { 29 | MapBrokerHostSettings(); 30 | MapClientSettings(); 31 | } 32 | 33 | private void MapBrokerHostSettings() 34 | { 35 | BrokerHostSettings brokerHostSettings = new BrokerHostSettings(); 36 | Configuration.GetSection(nameof(BrokerHostSettings)).Bind(brokerHostSettings); 37 | AppSettingsProvider.BrokerHostSettings = brokerHostSettings; 38 | } 39 | 40 | private void MapClientSettings() 41 | { 42 | ClientSettings clientSettings = new ClientSettings(); 43 | Configuration.GetSection(nameof(ClientSettings)).Bind(clientSettings); 44 | AppSettingsProvider.ClientSettings = clientSettings; 45 | } 46 | 47 | public void ConfigureServices(IServiceCollection services) 48 | { 49 | services.AddMqttClientHostedService(); 50 | services.AddSingleton(); 51 | } 52 | 53 | // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 54 | public void Configure(IApplicationBuilder app, IWebHostEnvironment env) 55 | { 56 | if (env.IsDevelopment()) 57 | { 58 | app.UseDeveloperExceptionPage(); 59 | } 60 | 61 | app.UseRouting(); 62 | 63 | app.UseEndpoints(endpoints => 64 | { 65 | endpoints.MapGet("/", async context => 66 | { 67 | await context.Response.WriteAsync("Hello World!"); 68 | }); 69 | }); 70 | } 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /appsettings.Development.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /appsettings.json: -------------------------------------------------------------------------------- 1 | { 2 | "Logging": { 3 | "LogLevel": { 4 | "Default": "Information", 5 | "Microsoft": "Warning", 6 | "Microsoft.Hosting.Lifetime": "Information" 7 | } 8 | }, 9 | 10 | "BrokerHostSettings": { 11 | "Host": "localhost", 12 | "Port": 1883 13 | }, 14 | 15 | "ClientSettings": { 16 | "Id": "5eb020f043ba8930506acbdd", 17 | "UserName": "rafiul", 18 | "Password": "12345678" 19 | }, 20 | 21 | "AllowedHosts": "*" 22 | } 23 | --------------------------------------------------------------------------------