Asp.net core 2.0 webapi integration signalr (instance description), webapisignalr

Source: Internet
Author: User

Asp.net core 2.0 webapi integration signalr (instance description), webapisignalr

I have been in the blog garden for many years and have never shared anything or wrote a blog, but I have learned the knowledge of the blog garden to grow;

These two days cannot be so selfless. Recently,. net core seems to be quite popular, and I made an asp.net core signalr myself.

Some people in the blog Park 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;

In addition, signalr involves the number of connections and memory resource usage issues. If both are integrated into a project, when the access volume is large, website access is easy to slow. The specific reasons are not mentioned.

So here I have integrated signalr in. net core webapi, so we can call webapi to push messages to the client.

Step 1Reference nuget: Mrcrosoft. AspNetCore. SignalR

Step 2Add configuration code:

Add the following code to ConfigureServices:

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

Add

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 an hubs

Public class SignalrHubs: hub {// <summary> /// create the signalr link /// </summary> /// <param name = "parentId"> pid (as a 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 C Lients. all. invokeAsync ("NoticeOnline", "the user group data has been updated, and the new id is:" + Context. connectionId + "pid:" + parentId + "sid:" + shopId + "");} public override Task OnDisconnectedAsync (Exception exception) {// Remove user var user = SignalrGroups from offline. 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 am here based on my own business needs. You can change it to another one (the memory usage is definitely high when the number of users is large. Here is a simple example)

The above basic environment has been set up.

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> // push a single connectionid /// </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 ("Ev EryOne ")] 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 Method /// </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 code is complete here. Next let's look at the client code.

My client code is in another project, which is separated from the server.

<Input type = "text" id = "ParentId" placeholder = "ParentId"/> <br/> <input type = "text" id = "ShopId" placeholder = "ShopId" /> <br/> <button id = "fuckyou"> Publish a user </button> <br/> <ul id = "message"> </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 ('noticeon', data =>{$ ("# message "). append ("<li>" + data + "</li>") ;}); hubConnection. on ('everone', data =>{$ ("# message "). append ("<li style = \" color: red; \ "> push all:" + data + "</li>") ;}); hubConnection. on ('anygroups', data =>{$ ("# message "). append ("<li style = \" color: black; \ "> push by a single user group:" + data + "</li>") ;}); 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; \ "> receiving multiple parameters:" + message + ": "+ data +" </li> ") ;}); hubConnection. start () ;}); </script>}

Reference a js connection on the page

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

This is basically done. Let's take a look at the running effect.

The first time I wrote a blog, I was a little nervous. The code was too hasty, and many details were not optimized. I hope you can correct me a lot.

The integration of the above asp.net core 2.0 webapi signalr (instance description) is all the content that I have shared with you. I hope to give you a reference and support for the customer's house.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.