Another one example of text messages exchange service. Based on the next libs list:
- ASP.NET Core 2.0;
- Yeoman generator;
- SignalR 1.0.0-preview1-final for ASP.NET Core 2.0;
- Angular 4.1.2;
- Typescript 2.7.2;
- Swagger 2.2.0 with Autorest API client codegen.
To implement SignalR usage on ASP.NET Core app you should:
- Create ASP.NET Core project:
dotnet new angular
- Download NPM packages:
npm install
- Add NuGet references to the next libs:
Microsoft.AspNetCore.All
;Microsoft.AspNetCore.SignalR
.
- Implement nested from
Hub
orHub<T>
class:
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR;
using SimpleChat.Models;
namespace SimpleChat.Hubs
{
public sealed class ChatHub: Hub<IChatHub>
{
public async Task Send(ChatMessageModel chatMessage)
{
if (chatMessage == null) throw new ArgumentNullException(nameof(chatMessage));
await Clients.All.SendAsync(chatMessage);
}
}
}
- Add support for the SignalR in
Startup.cs
. Enable SignalR for our application:
services.AddSignalR();
Create route mapping for our SignalR's chat Hub implementation:
app.UseSignalR(routes =>
// Note: chat hub name should start with '/'
routes.MapHub<ChatHub>("/chathub")
);
Note:: hub name should start with '/'. 6. Install the latest version of the ASP.NET Core SignalR NPM package:
npm install @aspnet/signalr
- Now we can create, setup and start SignalR's HubConnection in a Typescript component:
this.chatHub = new HubConnection(originUrl + "/chathub");
this.chatHub.on(
"Send",
data => this.receiveMessage(data));
this.chatHub
.start()
.catch(error => console.log(error));
- Profit! That is all. Now we can start our chat:
dotnet run
Note: Windows authentification is used by default.
- Install Swagger NuGet package:
Install-package Swashbuckle.AspNetCore
- Initalize Swagger UI module in your Startup.cs
Configure()
method:
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Chat API V1");
});
- Enable XML documentation generation in your project settings;
- Specify Swagger generation settings in
Startup.cs
classConfigureServices()
method:
services.AddSwaggerGen(c =>
{
c.SwaggerDoc(
"v1",
new Info
{
Title = "SimpleChat API",
Version = "v1"
});
var basePath = PlatformServices.Default.Application.ApplicationBasePath;
var xmlPath = Path.Combine(basePath, "SimpleChat.xml");
c.IncludeXmlComments(xmlPath);
});
- OpenAPI SimpleChat API definition can be found:
https://localhost:44395/swagger/
- Yeoman's home page on GitHub: https://github.com/OmniSharp/generator-aspnet
- SignalR home page on GitHub: https://github.com/aspnet/SignalR
- SignalR for ASP.NET Core 2.0: https://blogs.msdn.microsoft.com/webdev/2017/09/14/announcing-signalr-for-asp-net-core-2-0/
- SignalR with Windows authentication: http://msharonov.blogspot.com/2017/10/signalr-windows-authentication.html
- Swagger: https://docs.microsoft.com/en-us/aspnet/core/tutorials/web-api-help-pages-using-swagger?tabs=visual-studio