Web Api请求引发“将内容复制到流时出错". [英] Web Api Request Throws "Error while copying content to a stream."

查看:118
本文介绍了Web Api请求引发“将内容复制到流时出错".的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现此代码示例,但得到 HttpRequestException -"将内容复制到流中时发生错误."调用 ReadAsStringAsync()方法时.内部的例外是"无法访问已处置的对象".我正在使用Fiddler发出请求.我不明白有人可以解释为什么我遇到此异常并提供解决方案吗?

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方法:

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);
}

提琴手(POST):

User-Agent: Fiddler
Host: localhost:23567
Content-Length: 18
Content-Type: application/json; charset=utf-8
Body{"Test":1}

我有一个线索,但需要验证.在Web Api控制器上,我有一个 ActionFilterAttribute ,在其 OnActionExecuting 覆盖中,有以下一行:

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();
}

可能是因为这里读取了内容,所以不再可用了吗?如果是这样,如何在方法中使用它?这里的内容与HttpRequestMessage相同吗?可能包含一个答案.

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.

推荐答案

由于控制器的 ActionFilterAttribute的 OnActionExecuting 方法正在调用 ReadAsStreamAsync ,因此内容无法再次读取.我将 ReadAsStreamAsync 更改为 ReadAsStringAsync ,请求的内容在控制器中可用.显然,ReadAsStringAsync会缓冲内容,使其仍然可用.此链接提供了答案.

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.

这篇关于Web Api请求引发“将内容复制到流时出错".的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆