重构代码:增加SignalRExceptionFilter过滤器,用于处理后台异常通知前台

This commit is contained in:
Argo-MacBookPro 2018-10-15 21:08:54 +08:00
parent 0d41c6500e
commit 10092a383d
4 changed files with 45 additions and 7 deletions

View File

@ -3,7 +3,9 @@ using Bootstrap.Security;
using Longbow.Web.SignalR; using Longbow.Web.SignalR;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
using System.Linq; using System.Linq;
using System.Threading.Tasks;
namespace Bootstrap.Admin.Controllers.Api namespace Bootstrap.Admin.Controllers.Api
{ {
@ -27,10 +29,10 @@ namespace Bootstrap.Admin.Controllers.Api
/// <param name="user"></param> /// <param name="user"></param>
/// <returns></returns> /// <returns></returns>
[HttpPost] [HttpPost]
public bool Post([FromServices]ISignalRHubContext<SignalRHub> hub, [FromBody]User user) public async Task<bool> Post([FromServices]IHubContext<SignalRHub> hub, [FromBody]User user)
{ {
var ret = UserHelper.SaveUser(user); var ret = UserHelper.SaveUser(user);
if (ret) hub.SendAll(new MessageBody() { Category = "Users", Message = string.Format("{0}-{1}", user.UserName, user.Description) }); if (ret) await SignalRManager.Send(hub.Clients.All, new MessageBody() { Category = "Users", Message = string.Format("{0}-{1}", user.UserName, user.Description) });
return ret; return ret;
} }
} }

View File

@ -0,0 +1,34 @@
using Bootstrap.DataAccess;
using Microsoft.AspNetCore.SignalR;
using System;
using System.Data.Common;
namespace Bootstrap.Admin
{
/// <summary>
///
/// </summary>
public static class SignalRManager
{
/// <summary>
///
/// </summary>
/// <param name="client"></param>
/// <param name="message"></param>
/// <returns></returns>
public static async System.Threading.Tasks.Task Send(IClientProxy client, MessageBody args) => await client.SendAsync("rev", args);
/// <summary>
///
/// </summary>
/// <param name="client"></param>
/// <param name="ex"></param>
/// <returns></returns>
public static async System.Threading.Tasks.Task Send<T>(IHubContext<T> context, Exception ex) where T : Hub
{
var category = "App";
if (ex.GetType().IsSubclassOf(typeof(DbException))) category = "DB";
var message = new MessageBody() { Category = category, Message = ex.Message };
await Send(context.Clients.All, message);
}
}
}

View File

@ -50,11 +50,13 @@ namespace Bootstrap.Admin
.SetApplicationName(Configuration["ApplicationName"]) .SetApplicationName(Configuration["ApplicationName"])
.PersistKeysToFileSystem(new DirectoryInfo(Configuration["KeyPath"])); .PersistKeysToFileSystem(new DirectoryInfo(Configuration["KeyPath"]));
if (Configuration["DisableAutomaticKeyGeneration"] == "True") dataProtectionBuilder.DisableAutomaticKeyGeneration(); if (Configuration["DisableAutomaticKeyGeneration"] == "True") dataProtectionBuilder.DisableAutomaticKeyGeneration();
services.AddSignalRManager(); services.AddSignalR().AddJsonProtocalDefault();
services.AddSignalRExceptionFilterHandler<SignalRHub>(async (client, ex) => await SignalRManager.Send(client, ex));
services.AddMvc(options => services.AddMvc(options =>
{ {
options.Filters.Add<BootstrapAdminAuthorizeFilter>(); options.Filters.Add<BootstrapAdminAuthorizeFilter>();
options.Filters.Add<ExceptionFilter>(); options.Filters.Add<ExceptionFilter>();
options.Filters.Add<SignalRExceptionFilter<SignalRHub>>();
}).AddJsonOptions(options => }).AddJsonOptions(options =>
{ {
options.SerializerSettings.ContractResolver = new DefaultContractResolver(); options.SerializerSettings.ContractResolver = new DefaultContractResolver();
@ -83,7 +85,7 @@ namespace Bootstrap.Admin
app.UseAuthentication(); app.UseAuthentication();
app.UseBootstrapAdminAuthorization(); app.UseBootstrapAdminAuthorization();
app.UseCacheManagerCorsHandler(); app.UseCacheManagerCorsHandler();
app.UseSignalR(routes => { routes.MapHub("/NotiHub"); }); app.UseSignalR(routes => { routes.MapHub<SignalRHub>("/NotiHub"); });
app.UseMvc(routes => app.UseMvc(routes =>
{ {
routes.MapRoute( routes.MapRoute(

View File

@ -50,7 +50,7 @@ namespace Bootstrap.Client
.SetApplicationName(Configuration["ApplicationName"]) .SetApplicationName(Configuration["ApplicationName"])
.PersistKeysToFileSystem(new DirectoryInfo(Configuration["KeyPath"])); .PersistKeysToFileSystem(new DirectoryInfo(Configuration["KeyPath"]));
if (Configuration["DisableAutomaticKeyGeneration"] == "True") dataProtectionBuilder.DisableAutomaticKeyGeneration(); if (Configuration["DisableAutomaticKeyGeneration"] == "True") dataProtectionBuilder.DisableAutomaticKeyGeneration();
services.AddSignalRManager(); services.AddSignalR().AddJsonProtocalDefault();
services.AddMvc(options => services.AddMvc(options =>
{ {
options.Filters.Add<BootstrapAdminAuthorizeFilter>(); options.Filters.Add<BootstrapAdminAuthorizeFilter>();
@ -83,14 +83,14 @@ namespace Bootstrap.Client
app.UseStatusCodePagesWithReExecute("/Home/Error/{0}"); app.UseStatusCodePagesWithReExecute("/Home/Error/{0}");
app.UseCors(builder => builder.WithOrigins(Configuration["AllowOrigins"].Split(',', StringSplitOptions.RemoveEmptyEntries)).AllowAnyHeader().AllowAnyMethod().AllowCredentials()); app.UseCors(builder => builder.WithOrigins(Configuration["AllowOrigins"].Split(',', StringSplitOptions.RemoveEmptyEntries)).AllowAnyHeader().AllowAnyMethod().AllowCredentials());
//app.UseHttpsRedirection(); app.UseHttpsRedirection();
app.UseStaticFiles(); app.UseStaticFiles();
app.UseCookiePolicy(); app.UseCookiePolicy();
app.UseAuthentication(); app.UseAuthentication();
app.UseBootstrapAdminAuthorization(); app.UseBootstrapAdminAuthorization();
app.UseWebSocketHandler(options => options.UseAuthentication = true); app.UseWebSocketHandler(options => options.UseAuthentication = true);
app.UseCacheManagerCorsHandler(); app.UseCacheManagerCorsHandler();
app.UseSignalR(routes => { routes.MapHub("/NotiHub"); }); app.UseSignalR(routes => { routes.MapHub<SignalRHub>("/NotiHub"); });
app.UseMvc(routes => app.UseMvc(routes =>
{ {
routes.MapRoute( routes.MapRoute(