繁体   English   中英

是否可以在 Middleware Asp .Net Core 中调用 WebApi

[英]Is it possible to call WebApi inside Middleware Asp .Net Core

我正在 MVC Aps.Net Core 项目上工作,我遇到了这种情况:

用户A登录设备A ,用户B尝试登录设备A 我允许用户B登录到设备A没有问题,但在这种情况下,我向用户A显示弹出消息,用户A现在与设备A断开连接。

Everrithing 工作正常。 我在具有 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>();
        }
    }
}

我得到这个错误

有没有可能以这种方式做到这一点? 任何建议如何解决这个问题? 提前致谢!

看起来您的中间件无权访问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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM