当前位置:网站首页>ASP. Send information in sinalr controller of net core
ASP. Send information in sinalr controller of net core
2022-06-30 15:40:00 【zhoubangbang1】
obtain IHubContext Example
stay ASP.NET Core SignalR, Instances you can access IHubContext Inject through dependencies . Instances that you can inject IHubContext To the controller 、 Middleware or others DI service . The instance used sends the message to the client .
Injected into the controller IHubContext There are two methods for instance
One :. Inject instances directly into IHubContext Add to The constructor of the controller :
Specific steps :
1. Inject instances directly into IHubContext Add to The constructor of the controller :
public class HomeController : Controller
{
private readonly IHubContext<ChatHub> _hubContext;
public HomeController(IHubContext<ChatHub> chatHubContext)
{
_hubContext = chatHubContext;
}
public async Task<IActionResult> Index()
{
return View();
}
}
2. To configure SignalR
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddSignalR();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseSignalR(routes =>
{
routes.MapHub<ChatHub>("/chatHub");
});
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}3. Generate Home View , Code :
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="initial-scale=1.0,maximum-scale=1.0,user-scalable=no">
<title>Test</title>
<script src="~/lib/jquery/dist/jquery.js"></script>
</head>
<body >
<div class="container">
<div class="row"> </div>
<div class="row">
<div class="col-6"> </div>
<div class="col-6">
User..........<input type="text" id="userInput" />
<br />
Message...<input type="text" id="messageInput" />
<input type="button" id="sendButton" value="Send Message" />
</div>
</div>
<div class="row">
<div class="col-12">
<hr />
</div>
</div>
<div class="row">
<div class="col-6"> </div>
<div class="col-6">
<ul id="messagesList"></ul>
</div>
</div>
</div>
<script src="~/lib/signalr/dist/browser/signalr.js"></script>
<script type="text/javascript">
const connection = new signalR.HubConnectionBuilder()
.withUrl("/chatHub")
.build();
connection.on("ReceiveMessage", (user, message, id) => {
const encodedMsg = user + " says " + message + " id:" + id ;
const li = document.createElement("li");
li.textContent = encodedMsg;
document.getElementById("messagesList").appendChild(li);
});
document.getElementById("sendButton").addEventListener("click", event => {
const user = document.getElementById("userInput").value;
const message = document.getElementById("messageInput").value;
connection.invoke("SendMessage", user, message).catch(err => console.error(err));
event.preventDefault();
});
connection.start().catch(err => console.error(err));
//connection.start();
</script>
</body>
</html>
4. Running results :

Two : Injection strong typing HubContext
1. take Strong type Injection into IHubContext Add to The constructor of the controller :
public class HomeController : Controller
{
// private readonly IHubContext<ChatHub> _hubContext;
private IHubContext<StronglyTypedChatHub, IChatClient> _hubContext { get; }
public HomeController(IHubContext<StronglyTypedChatHub, IChatClient> chatHubContext)
{
_hubContext = chatHubContext;
}
public async Task<IActionResult> Index()
{
return View();
}
}2. To configure SignalR
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseSignalR(routes =>
{
routes.MapHub<StronglyTypedChatHub>("/chatHub");
});
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
3. Generate Home View , Code :
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="initial-scale=1.0,maximum-scale=1.0,user-scalable=no">
<title>Test</title>
<script src="~/lib/jquery/dist/jquery.js"></script>
</head>
<body >
<div class="container">
<div class="row"> </div>
<div class="row">
<div class="col-6"> </div>
<div class="col-6">
User..........<input type="text" id="userInput" />
<br />
Message...<input type="text" id="messageInput" />
<input type="button" id="sendButton" value="Send Message" />
</div>
</div>
<div class="row">
<div class="col-12">
<hr />
</div>
</div>
<div class="row">
<div class="col-6"> </div>
<div class="col-6">
<ul id="messagesList"></ul>
</div>
</div>
</div>
<script src="~/lib/signalr/dist/browser/signalr.js"></script>
<script type="text/javascript">
const connection = new signalR.HubConnectionBuilder()
.withUrl("/chatHub")
.build();
connection.on("ReceiveMessage", (user, message, id) => {
const encodedMsg = user + " says " + message + " id:" + id ;
const li = document.createElement("li");
li.textContent = encodedMsg;
document.getElementById("messagesList").appendChild(li);
});
document.getElementById("sendButton").addEventListener("click", event => {
const user = document.getElementById("userInput").value;
const message = document.getElementById("messageInput").value;
connection.invoke("SendMessage", user, message).catch(err => console.error(err));
event.preventDefault();
});
connection.start().catch(err => console.error(err));
//connection.start();
</script>
</body>
</html>
4. Running results :

边栏推荐
- C language \t usage
- J - Borg maze (minimum spanning tree +bfs)
- I - constructing roads
- LeCun指明下一代AI方向:自主机器智能
- Scattered knowledge of C language (unfinished)
- 1077 kuchiguse (20 points)
- The principle of fluent 2 rendering and how to realize video rendering
- Advanced C language - pointer 3 - knowledge points sorting
- 深入理解.Net中的线程同步之构造模式(二)内核模式1.内核模式构造物Event事件
- [leetcode] linked list sorting (gradually increasing the space-time complexity)
猜你喜欢

The principle of fluent 2 rendering and how to realize video rendering

ADB devices cannot detect the problem of Xiaomi note 3

Policy Center-User Data

比亚迪越来越像华为?

Policy Center > Google Play‘s Target API Level Policy

各省GDP可视化案列,附带csv Metabase处理

Create a new MySQL database under Linux and import SQL files

(Niuke) BFS

Summary of gradient descent optimizer (rmsprop, momentum, Adam)

【子矩阵数量统计】CF1181C Flag子矩阵数量统计
随机推荐
4.7 type() function query data type
[leetcode] linked list sorting (gradually increasing the space-time complexity)
Jupyter notebook basic knowledge learning
Joint examination for management -- sample composition
C language \t usage
E - highways (minimum spanning tree)
Message queue ten questions
NPM install --global --save --save dev differences
map reduce案例超详细讲解
智慧风电:数字孪生 3D 风机智能设备运维
Model system: Sword (1)
Developer practice - the future of Agora home AI audio and video
Voice codec based on machine learning Agora silver: support high quality voice interaction at ultra-low bit rate
Openresty built in variable
Curl: (23) failed writing body (1354 i= 1371) problem solving method
Talk about why I started technical writing
Explain service idempotency design in detail
The principle of fluent 2 rendering and how to realize video rendering
Policy Center-Permissions and APIs that Access Sensitive Information
Advanced C language - pointer 3 - knowledge points sorting