【发布时间】:2020-09-16 14:09:26
【问题描述】:
我正在开发一个 MVC Aps.Net Core 项目,我遇到了这种情况:
用户A已登录设备A,用户B正在尝试登录设备A。我允许用户 B 毫无问题地登录设备 A,但在这种情况下,我会向用户 A 显示弹出消息,该用户 A 现在已与设备 A 断开连接。
一切正常。我在有 SQL 函数的地方调用 WebApi,该函数完成所有工作。问题是我项目的每个函数中都有相同的代码(调用 WebApi)。所以我正在考虑制作自定义中间件,这样我就不需要在项目中的每个函数/方法中替换该代码。
这是我尝试过的:
public class Middleware
{
private readonly RequestDelegate _next;
string strBaseUrl = string.Empty;
string strMappaturaUrl = string.Empty;
private readonly IConfiguration config;
private readonly HttpClient client;
public Middleware(RequestDelegate next, IConfiguration _config, HttpClient _client)
{
_next = next;
client = _client;
config = _config;
strBaseUrl = config.GetValue<string>("AppSettings:BaseUrl");
strMappaturaUrl = config.GetValue<string>("AppSettings:MapUrl");
}
public async Task Invoke(HttpContext httpContext)
{
string returnErrore = string.Empty;
CheckUtenteDTO userRequest = new CheckUtenteDTO();
string strUrlApi = string.Empty;
string strContext = string.Empty;
try
{
userRequest.user = HttpContext.Session.GetString("nomeUten");
userRequest.macchina = HttpContext.Session.GetString("macchina");
//Here I call WebApi where I have SQL functio
strUrlApi = config.GetValue<string>("AppSettings:BaseUrl") + "/Users/CheckLoginUser";
string stringData = JsonConvert.SerializeObject(userRequest);
var contentData = new StringContent(stringData, System.Text.Encoding.UTF8, "application/json");
using (var responseMessage = await client.PostAsync(strUrlApi, contentData))
{
if (responseMessage.IsSuccessStatusCode)
{
strContext = await responseMessage.Content.ReadAsStringAsync();
var strReturn = JsonConvert.DeserializeObject<string>(strContext);
if (string.IsNullOrWhiteSpace(strReturn))
returnErrore = string.Empty;
else
throw new UtenteException(strReturn);
}
else
{
strContext = await responseMessage.Content.ReadAsStringAsync();
throw new Exception(strContext);
}
}
}
catch (UserException ex1)
{
returnErrore = ex1.Message.Trim();
HttpContext.Session.SetString("strErrore", ex1.Message);
HttpContext.Session.SetString("nextAction", "LogoutAfterCheck");
HttpContext.Session.SetString("nextController", "Login");
}
catch (Exception ex)
{
returnErrore = ex.Message.Trim();
HttpContext.Session.SetString("strErrore", ex.Message);
HttpContext.Session.SetString("nextAction", "Index");
HttpContext.Session.SetString("nextController", "HomeScreen");
}
return Json(returnErrore);
//return _next(httpContext);
}
}
// Extension method used to add the middleware to the HTTP request pipeline.
public static class MiddlewareExtensions
{
public static IApplicationBuilder UseMiddleware(this IApplicationBuilder builder)
{
return builder.UseMiddleware<Middleware>();
}
}
}
我得到了这个errors 。
这样可以吗? 任何建议如何解决这个问题? 提前致谢!
【问题讨论】:
标签: c# asp.net asp.net-mvc asp.net-core model-view-controller