小编Chr*_*sMB的帖子

在自定义中间件中测试 response.WriteAsync()

我有一个 ASP.NET Core API,我为它编写了自定义中间件,以便我可以在一个地方处理异常和写入日志。当通过 Kestrel 调试并从浏览器或邮递员提交请求时,中间件按要求工作,但是在我的测试中,响应正文始终是空流。

下面是我编写的中间件类和测试,context.Response.WriteAsync(result) 由于某种原因似乎没有刷新流,但我不知道为什么。有谁能解释一下吗?

using System;
using System.Net;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using Microsoft.Extensions.Logging;
using System.IO;

namespace APP.API.Middleware
{
    public class ExceptionHandler
    {
        private readonly RequestDelegate request;
        private readonly ILogger logger;

        public ExceptionHandler(RequestDelegate request, ILogger<ExceptionHandler> logger)
        {
            this.request = request;
            this.logger = logger;
        }

        public async Task Invoke(HttpContext context)
        {
            try
            {
                await request(context);
            }
            catch (Exception ex)
            {
                await HandleExceptionAsync(context, ex);
            }
        }

        private Task HandleExceptionAsync(HttpContext context, Exception ex)
        {
            HttpStatusCode statusCode = …
Run Code Online (Sandbox Code Playgroud)

c# mstest asp.net-core

9
推荐指数
1
解决办法
2828
查看次数

标签 统计

asp.net-core ×1

c# ×1

mstest ×1