using Microsoft.AspNetCore.SignalR;
using System.Threading.Tasks;
namespace UeaseMan.Server.Hubs
{
public class ChatHub : Hub
{
/// <summary>
/// for 非同步呼送訊息
/// </summary>
public async Task SendMessage(string user, string message)
{
await Task.Run(() =>
{
// SignalR 回送訊息給傳訊息
Clients.Caller.SendAsync("HasSentMessage", user, message);
// SingalR 轉送訊息給全部線上使用者
Clients.All.SendAsync("ReceiveMessage", user, message);
});
}
/// <summary>
/// for 同步呼叫並回傳值
/// </summary>
public async Task<string> PostFormData(string user, string message)
{
string result = "未處理";
result = await Task.Run<string>(() =>
{
Clients.Caller.SendAsync("HasSentMessage", user, message);
return $"收到訊息:{user}:{message}";
});
return result;
}
}
}
Startup.cs
using ......
using UeaseMan.Server.Hubs; //※※※ ------
namespace UeaseMan.Server
{
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.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddSignalR(); //※ 新增 SignalR 軟體服務 ------
services.AddControllersWithViews();
services.AddRazorPages();
services.AddMudServices();
//※ 新增回應壓縮中介軟體服務 ------
services.AddResponseCompression(opts =>
{
opts.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(
new[] { "application/octet-stream" });
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
//※ 在處理管線的設定頂端使用回應壓縮中介軟體。 ------
app.UseResponseCompression();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseWebAssemblyDebugging();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseBlazorFrameworkFiles();
app.UseStaticFiles();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
endpoints.MapControllers();
//※ 在控制器的端點和用戶端的回復之間,新增中樞的端點。 ------
endpoints.MapHub<ChatHub>("/chathub");
endpoints.MapFallbackToFile("index.html");
});
}
}
}