I'm trying to implement this code example, but get a HttpRequestException
- "Error while copying content to a stream." when the ReadAsStringAsync()
method is called. The inner exception is "Cannot access a disposed object." I'm using Fiddler to make the request. I don't understand. Can someone explain why I'm getting this exception and offer a solution?
Web Api Method:
public async Task<HttpResponseMessage> Post(HttpRequestMessage request)
{
try
{
var jsonString = await request.Content.ReadAsStringAsync();
}
catch (Exception ex)
{
throw;
}
return new HttpResponseMessage(HttpStatusCode.Created);
}
Fiddler (POST):
User-Agent: Fiddler
Host: localhost:23567
Content-Length: 18
Content-Type: application/json; charset=utf-8
Body{"Test":1}
Edit:
I have a clue, but need verification. On the Web Api controller, I have an ActionFilterAttribute
and in its OnActionExecuting
override, there's this line:
public override async void OnActionExecuting(HttpActionContext actionContext)
{
// omitted code
actionContext.Request.Content.ReadAsStreamAsync();
}
Could it be that because the Content is read here, it's not available again? If so, how can I make it available in the method? Is the Content here the same as the HttpRequestMessage? This may contain an answer.
Because the controller's ActionFilterAttribute's
OnActionExecuting
method is calling ReadAsStreamAsync
, the Content can't be read again. I changed ReadAsStreamAsync
to ReadAsStringAsync
and the request's Content is available in the controller. Apparantly, ReadAsStringAsync buffers the Content so it's still available. This link provided the answer.