首页 新闻 会员 周边

ASP.NET Core中InvalidOperationException异常: Headers are read-only, response has already started

0
悬赏园豆:30 [已解决问题] 解决于 2017-02-16 14:16

具体的异常信息如下:

System.InvalidOperationException: Headers are read-only, response has already started.
   at Microsoft.AspNetCore.Server.Kestrel.Internal.Http.FrameHeaders.ThrowHeadersReadOnlyException()
   at Microsoft.AspNetCore.Server.Kestrel.Internal.Http.FrameHeaders.Microsoft.AspNetCore.Http.IHeaderDictionary.set_Item(String key, StringValues value)
   at Cnblogs.Web.ErrorPages.ErrorPage.<>c__DisplayClass1_0.<<ResponseWriteAsync>b__0>d.MoveNext()

异常发生于下面的代码:

public static class ErrorPage
{
    public static async Task ResponseAsync(HttpResponse response, int statusCode)
    {
        if (statusCode == 404)
        {
            //...
        }
    }
}

 

dudu的主页 dudu | 高人七级 | 园豆:30994
提问于:2017-02-16 12:00
< >
分享
最佳答案
1

回调时使用如下回调看看:
context.Response.OnStarting((state) =>
{
if (context.Response.StatusCode == 404)
{
.....
}
return Task.FromResult(0);
}, null);


收获园豆:30
Jeffcky | 老鸟四级 |园豆:2789 | 2017-02-16 13:08
其他回答(3)
0

重新 create 一个新的 HttpResponse

可能是当前传入的这个response已经生成了,生成之后就不允许再进行修改了。

nil | 园豆:879 (小虾三级) | 2017-02-16 12:29
0

response.WriteAsync之前,先检测一下response是否已经生成了。(可以通过HttpContext.Response.HasStarted属性判断)


蝌蝌 | 园豆:158 (初学一级) | 2017-02-16 13:12
0

好东西好东西好东西

weisp | 园豆:3 (初学一级) | 2017-06-20 13:27
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册