Getting empty response on asp.net core middleware on exception

后端 未结 2 1661
刺人心
刺人心 2021-01-18 12:39

I am trying to create a middleware that can log the response body as well as manage exception globally and I was succeeded about that. My problem is that the custom message

2条回答
  •  走了就别回头了
    2021-01-18 12:52

    I think what you are saying is that this code isn't sending it's response to the client.

     catch (Exception ex)
        {
            context.Response.ContentType = "application/json";
            context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
            var jsonObject = JsonConvert.SerializeObject(My Custom Model);
            await context.Response.WriteAsync(jsonObject, Encoding.UTF8);
            return;
        }
    

    The reason for this is that await context.Response.WriteAsync(jsonObject, Encoding.UTF8); isn't writing to the original body stream it's writing to the memory stream that is seekable. So after you write to it you have to copy it to the original stream. So I believe the code should look like this:

     catch (Exception ex)
        {
            context.Response.ContentType = "application/json";
            context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
            var jsonObject = JsonConvert.SerializeObject(My Custom Model);
            await context.Response.WriteAsync(jsonObject, Encoding.UTF8);
    
            context.Response.Body.Seek(0, SeekOrigin.Begin);    //IMPORTANT!
            await responseBody.CopyToAsync(originalBodyStream); //IMPORTANT!
            return;
        }
    

提交回复
热议问题