0

I am trying to send my cached response back to the client but have an error

System.InvalidOperationException: The response cannot be cleared, it has already started sending.

I am trying to modify response to prevent sending my request further to third-party API

var result = await priceFilter.ValidateRequest(document);

if (result != null && !_httpContext.Response.HasStarted)
{
    HttpResponse response = _httpContext.Response;
    response.Clear();
    var buffer = Encoding.UTF8.GetBytes(result);

    response.StatusCode = 200;
    response.ContentType = "text/xml;charset=utf-8";
    response.ContentLength = buffer.Length;
    await response.Body.WriteAsync(buffer, 0, buffer.Length);     
}
Parmiz
  • 1

1 Answers1

1

This error typically occurs when you try to modify the response after it has already been sent to the client. In your case, it could be that the response has already been sent to the client before you try to modify it, which is why you are seeing this error.

One way to prevent this error is to check whether the response has already started before attempting to modify it. In your code, you are checking whether the response has started using _httpContext.Response.HasStarted, which is correct. However, you are also calling response.Clear() before modifying the response, which may be causing the error.

Instead of calling response.Clear(), you can simply modify the properties of the existing response object.

var result = await priceFilter.ValidateRequest(document);
    
if (result != null && !_httpContext.Response.HasStarted)
{
    var response = _httpContext.Response;
    response.StatusCode = 200;
    response.ContentType = "text/xml;charset=utf-8";
    
    var buffer = Encoding.UTF8.GetBytes(result);
    response.ContentLength = buffer.Length;
    await response.Body.WriteAsync(buffer, 0, buffer.Length);     
}

By modifying the properties of the response object without calling response.Clear(), you can ensure that the response is not modified after it has been sent to the client, preventing the "System.InvalidOperationException" error.

magmyr01
  • 13
  • 4
  • Yes this function call was just an attempt to avoid that error I tried almost all possible solutions but still have this error. For me it seems like YARP can modify response after my changes – Parmiz Apr 25 '23 at 17:12