【问题标题】:Is it possible to call WebApi inside Middleware Asp .Net Core是否可以在中间件 Asp .Net Core 中调用 WebApi
【发布时间】: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


    【解决方案1】:

    看起来您的中间件无权访问HttpContext,因此出现错误。在这种情况下,您可以将上下文作为参数从您可以访问 HttpContext 并调用中间件函数的表示层传递给中间件。

    本质上,您只使用会话中的以下两个参数.. 那么为什么不将它们提取到您的表示层并将它们作为参数传递给中间件函数

    userRequest.user = HttpContext.Session.GetString("nomeUten");
    userRequest.macchina = HttpContext.Session.GetString("macchina");
    

    将您的 Invoke 方法签名更改为

    Task Invoke(string user, string macchina) //assuming both are type string
    

    【讨论】:

      猜你喜欢
      • 2019-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-07
      • 2022-01-09
      • 1970-01-01
      • 2020-08-09
      相关资源
      最近更新 更多