当前位置:网站首页>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 :

边栏推荐
- 1082 read number in Chinese (25 points)
- A little idea about big experiment data
- Is Domain Driven Design (DDD) reliable?
- Tetris source code (color version)
- Openresty built in variable
- Operator%
- Specific steps for installing mysql8.0 on Windows system
- 《你的灯亮着吗》开始解决问题前,得先知道“真问题”是什么
- Alibaba cloud OSS object storage cross domain settings
- Technology sharing | anyrtc service single port design
猜你喜欢

FoxPro and I

Webrtc: industrial application based on Internet of things

4.4 string

Teach you a learning method to quickly master knowledge

topic: Privacy, Deception and Device Abuse

Modifying MySQL password under Linux: error 1396 (HY000): Operation alter user failed for 'root' @ 'localhost‘

What would you choose between architecture optimization and business iteration?

智慧风电:数字孪生 3D 风机智能设备运维

Anyrtc implements application scenarios based on webrtc

Complement (Niuke)
随机推荐
Joint examination for management -- sample composition
C language \t usage
1031 Hello world for u (20 points)
Explain service idempotency design in detail
Help you accumulate audio and video knowledge, Agora developer's roaming guide officially set sail
容器常用命令
linux下新建Mysql数据库并导入sql文件
Summary of gradient descent optimizer (rmsprop, momentum, Adam)
Practical cases of data visualization (timeline rotation diagram, streamlit control year metabase visualization tutorial) 2.0
Modifying MySQL password under Linux: error 1396 (HY000): Operation alter user failed for 'root' @ 'localhost‘
Container common commands
NPM install --global --save --save dev differences
[sub matrix quantity statistics] cf1181c flag sub matrix quantity statistics
FoxPro and I
Npumcm selection question 3 and acmc2020a
Tetris source code (color version)
It's so brain - burning that no wonder programmers lose their hair
Jupyter notebook basic knowledge learning
Developer practice - the future of Agora home AI audio and video
RTC monthly tabloid programming challenge ended successfully in June; Review of the first anniversary of sound network's listing