【问题标题】:Asp.Net core: call a custom method after response is returned from another middlewareAsp.Net core:从另一个中间件返回响应后调用自定义方法
【发布时间】:2017-08-03 03:36:20
【问题描述】:

我不熟悉 C# 中的异步模式并尝试使用 Asp.Net 核心。

我想在 Middleware_NotifyWPF 中的控制器操作收到响应后调用 InformUI() 方法。 怎么做? [类似于 Middleware_NotifyWPF 的 request.on('end') 事件处理程序。]

Startup.cs:

  public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            app.Middleware_NotifyWPF();
            app.UseMvc();
        }

中间件 1:

    public class Middleware_NotifyWPF
        {
            private readonly RequestDelegate _next;
            private static Logger _logger = LogManager.GetCurrentClassLogger();

            public Middleware_NotifyWPF(RequestDelegate next)
            {
                _next = next;
            }

            public Task Invoke(HttpContext httpContext)
            {
                return _next(httpContext);


                InformUI(httpContext.Request, httpContext.Response); //Unreachable code
            }
}

控制器类 |动作方法

        [HttpGet("{id}")]
        public string Get(int id)
        {
            return "value";
        }

【问题讨论】:

  • 当然代码在 return 语句后是不可访问的,你期望什么?将方法更改为async Task,使用await _next(httpContext) 并删除该return 语句

标签: c# asp.net-core


【解决方案1】:

您需要等待任务才能在之后访问代码

public async Task Invoke(HttpContext httpContext)
{
    await _next(httpContext);

    InformUI(httpContext.Request, httpContext.Response); 
}

【讨论】:

    猜你喜欢
    • 2018-08-24
    • 1970-01-01
    • 2020-02-20
    • 2018-08-15
    • 2021-02-10
    • 2021-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多