asp.net Core 2.0 webapi integration signalr

Time:2020-10-21

I have been in the blog Garden for many years. I haven’t shared anything or written a blog, but I have learned from the knowledge of the blog Garden;

These two days, I think I can’t be so selfless. Recently. Net core seems to be very popular, and I’ve made one myself asp.net core signalr

Some people in the blog Garden have integrated signalr under. Net core 2.0, but they are integrated in the same project, but we all know that many of our projects are separated;

Moreover, signalr involves the number of connections and the occupation of memory resources. If they are integrated into a project, when the number of visits is large, it is easy to cause slow website access, and the specific reasons will not be discussed

Therefore, I have made an integration of signalr in. Net core webapi, and we can push messages from the server to the client by calling webapi

The first stepReference nuget: Mrcrosoft.AspNetCore.SignalR

Step twoAdd configuration code:

First, add the following code to configure services:


public void ConfigureServices(IServiceCollection services)
  {
   services.AddSignalR();
   services.AddCors(options =>
   {
    options.AddPolicy("SignalrCore",
     policy => policy.AllowAnyOrigin()
         .AllowAnyHeader()
         .AllowAnyMethod());
   });
   services.AddSingleton<IServiceProvider, ServiceProvider>();
  }

Then add it in configure

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
  {
   if (env.IsDevelopment())
   {
    app.UseDeveloperExceptionPage();
   }
   //Cross domain support
   app.UseCors("SignalrCore");
   app.UseSignalR(routes =>
   {
    routes.MapHub<SignalrHubs>("signalrHubs");
   });
   app.UseWebSockets();

   app.UseMvc();
  }

Then we add a hub

public class SignalrHubs:Hub
 {
  /// <summary>
  ///Create a signalr link
  /// </summary>
  ///< param name = "parentid" > PID (as user group) < / param >
  /// <param name="shopId">sid</param>
  public Task InitUser(string parentId, string shopId)
  {
   Groups.AddAsync(Context.ConnectionId, parentId);
   SignalrGroups.UserGroups.Add(new SignalrGroups()
   {
    ConnectionId = Context.ConnectionId,
    GroupName = parentId,
    ShopId = shopId
   });
   return  Clients.All.InvokeAsync ("noticeunline", "user group data update completed, new ID is:+ Context.ConnectionId  + " pid:" + parentId + " sid:" + shopId + "");
  }

  public override Task OnDisconnectedAsync(Exception exception)
  {
   //Remove users by dropping the line
   var user = SignalrGroups.UserGroups.FirstOrDefault(c => c.ConnectionId == Context.ConnectionId);
   if (user != null)
   {
    SignalrGroups.UserGroups.Remove(user);
    Groups.RemoveAsync(Context.ConnectionId, user.GroupName);
   }
   return base.OnDisconnectedAsync(exception);
  }
 }

PS: I do it according to my business needs. You can modify it to other ones (when the number of users is large, the memory consumption must be high. Here is just a simple example)

The above basic environment construction has been completed

Next, the code in the controller

[Produces("application/json")]
 [Route("api/MRSoftPush")]
 public class MRSoftPushController : Controller
 {
  private IHubContext<SignalrHubs> hubContext;
  public MRSoftPushController(IServiceProvider service)
  {
   hubContext = service.GetService<IHubContext<SignalrHubs>>();
  }

  [HttpGet]
  public string Get()
  {
   return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ffff");
  }

  /// <summary>
  ///Single connectionid push
  /// </summary>
  /// <param name="groups"></param>
  /// <returns></returns>
  [HttpPost,Route("AnyOne")]
  public IActionResult AnyOne([FromBody]IEnumerable<SignalrGroups> groups)
  {
   if (groups != null && groups.Any())
   {
    var ids = groups.Select(c=>c.ShopId);
    var list = SignalrGroups.UserGroups.Where(c=>ids.Contains(c.ShopId));
    foreach (var item in list)
     hubContext.Clients.Client(item.ConnectionId).InvokeAsync("AnyOne", $"{item.ConnectionId}: {item.Content}");
   }
   return Ok();
  }

  /// <summary>
  ///Push all
  /// </summary>
  /// <param name="message"></param>
  /// <returns></returns>
  [HttpGet,Route("EveryOne")]
  public IActionResult EveryOne(string message)
  {
   hubContext.Clients.All.InvokeAsync("EveryOne", $"{message}");
   return Ok();
  }

  /// <summary>
  ///Group push
  /// </summary>
  /// <param name="group"></param>
  /// <returns></returns>
  [HttpPost,Route("AnyGroups")]
  public IActionResult AnyGroups([FromBody]SignalrGroups group)
  {
   if (group != null)
   {
    hubContext.Clients.Group(group.GroupName).InvokeAsync("AnyGroups", $"{group.Content}");
   }
   return Ok();
  }

  /// <summary>
  ///Multi parameter receiving mode
  /// </summary>
  /// <param name="message"></param>
  /// <returns></returns>
  [HttpGet,Route("MoreParamsRequest")]
  public IActionResult MoreParamsRequest(string message)
  {
   hubContext.Clients.All.InvokeAsync("MoreParamsRequest", message, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ffff"));
   return Ok();
  }
 }

The server-side code is completed here. Next, let’s look at the client code

My client code is in another project, separate from the server

<input type="text" placeholder="ParentId" />
<br />
<input type="text" placeholder="ShopId" />
<br />
< button > users go online
<br />
<br />
<br />

<ul ></ul>

@section scripts {
 <script>
  $(function () {

   let hubUrl = 'http://192.168.0.149:8009/signalrHubs';
   let httpConnection = new signalR.HttpConnection(hubUrl);
   let hubConnection = new signalR.HubConnection(httpConnection);
   $("#fuckyou").click(function () {
    hubConnection.invoke('InitUser', $("#ParentId").val(), $("#ShopId").val());
   });
   hubConnection.on('NoticeOnline', data => {
    $("#message").append("<li>" + data + "</li>");
   });
   hubConnection.on('EveryOne', data => {
    $("#message").append("<li style=\" color:red; \"> push all:" data + "< / Li >");
   });
   hubConnection.on('AnyGroups', data => {
    $("#message").append("<li style=\" color:black; \"< Li" > "> single push group;
   });
   hubConnection.on('AnyOne', data => {
    $("#message").append("<li style=\" color:blue; \"> single ID push: + data +" < / Li > ");
   });
   hubConnection.on('MoreParamsRequest', (message, date) => {
    $("#message").append("<li style=\" color:green; \"> multi parameter reception: + message +": "+ data +" < / Li > ");
   });
   hubConnection.start();

  });
 </script>
}

A JS is referenced on the page

<script src=”/js/signalr-client.min.js”></script>
<script src=”/js/jquery.min.js”></script>

Here we have basically finished. Let’s take a look at the running effect

The first time I wrote a blog, I was a little nervous. The code was written in a hurry. Many details were not optimized. There are many shortcomings. I hope you can point out more

The above article asp.net Core 2.0 webapi integration signalr (example explanation) is all the content that Xiaobian shares with you. I hope it can give you a reference, and I hope you can support developpaer more.

Recommended Today

Summary of computer foundation for 2021 autumn recruitment interview database, redis

Series of articles: Summary of computer foundation in autumn 2021 interview algorithm, data structure, design pattern, Linux Summary of computer foundation in autumn 2021 interview – Java foundation, JVM, spring framework Summary of computer foundation for 2021 autumn recruitment interview database, redis Summary of computer foundation for 2021 autumn recruitment interview – operating system Summary […]