ASP. NET Core 2.0 WEBAPI integrated SIGNALR

Source: Internet
Author: User

In the blog park also for many years, has not shared anything, and did not write a blog, but I also learned from the blog Park Knowledge Growth;

These two days think not so selfless, recently. NET core seems to be very popular, free to do nothing also own a net core SIGNALR

There are also people in the blog park that have integrated SIGNALR under. NET Core 2.0, but are integrated in the same project, but we all know that many of our projects are separate;

and SIGNALR related to the number of connections and memory resources, if it is integrated in a project when the amount of traffic is easy to cause site access slow, the specific reason is not much to say

So here I do a. NET core WEBAPI integrated SIGNALR, we can call Webapi to implement the server to push the message to the client

The first step refers to Nuget:Mrcrosoft.AspNetCore.SignalR

The second step is to add the configuration code:

First, add the following code to the Configureservices:

public void Configureservices (iservicecollection services)        {            services. ADDSIGNALR ();            Services. Addcors (options =                options. Addpolicy ("Signalrcore",                    policy = policy. Allowanyorigin ()                                    . Allowanyheader ()                                    . Allowanymethod ());            });            Services. Addsingleton<iserviceprovider, serviceprovider> ();        }

Then add the Configure inside

public void Configure (Iapplicationbuilder app, ihostingenvironment env)        {            if (env. Isdevelopment ())            {                app. Usedeveloperexceptionpage ();            }            Support apps across domains            . Usecors ("Signalrcore");            App. USESIGNALR (routes =            {                routes. Maphub<signalrhubs> ("Signalrhubs");            });            App. Usewebsockets ();            App. Usemvc ();        }

Then we add a hubs

public class Signalrhubs:hub {//<summary>//Create SIGNALR link///</summary>// <param name= "ParentID" >pid (as user group) </param>//<param name= "Shopid" >sid</param> Publ            IC 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 ("Noticeonline", "User group data update complete, new ID:" + context.connectionid + "pid:" + ParentID + "SID:"        + Shopid + ""); } public override Task Ondisconnectedasync (Exception Exception) {//Drop line remove user var            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 am here according to my business needs to do, we can modify into other (user volume when the memory consumption is high, here only to do a simple example)

The above basic environmental construction has been completed

Then the code inside 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 A Nyone ([frombody]ienumerable<signalrgroups> groups) {if (groups! = null && groups. Any ()) {var ids = groups.                Select (C=&GT;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>//All push//</summary>//<param name= "message" ></param >//<returns></returns> [Httpget,route ("Everyone")] public Iactionresult EveryOne (St            Ring message) {HubContext.Clients.All.InvokeAsync ("EveryOne", $ "{message}");        return Ok (); }///<summary>//Group push///</summary>//<param name= "group" ></param&gt        ; <returns></returns> [Httppost,route ("anygroups")] public iactionresult anygroups ([frombody]s Ignalrgroups group) {if (group! = null) {HubContext.Clients.Group (group. GroupName). InvokeAsync ("Anygroups", $ "{group.  Content} ");          } return Ok (); }///<summary>///multi-parameter reception///</summary>//<param name= "message" ></pa  ram>//<returns></returns> [Httpget,route ("Moreparamsrequest")] public Iactionresult Moreparamsrequest (String message) {HubContext.Clients.All.InvokeAsync ("moreparamsrequest", Message, Da            TeTime.Now.ToString ("Yyyy-mm-dd HH:mm:ss:ffff"));        return Ok (); }    }

The server-side code is all done here, so let's look at the client's code

My client code is in another project, and the server side is separate

<input type= "text" id= "ParentID" placeholder= "ParentID"/><br/><input type= "text" id= "ShopId" Placeholder= "Shopid"/><br/><button id= "Fuckyou" > Users on-line </button><br/><br/><br/ ><ul id= "message" style= "color:red;" ></ul> @section Scripts {<script> $ (function () {Let Huburl = ' Http://192.168.0.149:8            009/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;\ "> All push:" + dat A + "</li>");           });  Hubconnection.on (' anygroups ', data = {$ ("#message"). Append ("<li style=\" color:black;\ "> Single user group push:"            + Data + "</li>");            }); Hubconnection.on (' anyone ', data = {$ ("#message"). Append ("<li style=\" color:blue;\ "> Single ID Push:" + da            Ta + "</li>");            }); Hubconnection.on (' Moreparamsrequest ', (message, date) = {$ ("#message"). Append ("<li style=\" color:gr            Een;\ "> Multi-parameter Receive:" + Message + ":" + Data + "</li>");            });        Hubconnection.start ();    }); </script>}

On the page to refer to a JS

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

The basic is done here, the following look at the effect of the operation

The first time to write a blog, a little nervous, code written in a hurry, a lot of details are not optimized, there are many shortcomings, I hope you are more correct.

ASP. NET Core 2.0 WEBAPI integrated SIGNALR

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.