ASP.NET Core中如果Response.HasStarted已经为true,就不能更改Response.Cookies和Response.Headers等属性的值了...

最近我在ASP.NET Core中做了一个中间件CustomizedMiddleware,要说该中间件的功能也很简单,其实就是往HttpResponse中添加一个Cookie而已,但是我将添加Cookie的代码放在了next.Invoke(context)的后面,如下所示:

using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;

namespace Assembly.Middlewares
{
    public class CustomizedMiddleware
    {
        private readonly RequestDelegate next;

        public CustomizedMiddleware(RequestDelegate next)
        {
            this.next = next;
        }

        public async Task Invoke(Microsoft.AspNetCore.Http.HttpContext context)
        {
            //Do something...
            await next.Invoke(context);
            //Do something...

            context.Response.Cookies.Append("DemoCookie", "DemoValue");//在next.Invoke(context)后添加Cookie到Response
        }
    }
}

结果代码执行到 context.Response.Cookies.Append("DemoCookie", "DemoValue")时,老是抛出异常。

后来查了查资料,原来HttpResponse中有个很重要的属性HasStarted,HttpResponse.HasStarted属性会返回一个bool类型的值,表示当前Http请求的响应(HttpResponse)是否已经把Http头(Header)的内容发送给客户端浏览器了,如果HttpResponse.HasStarted返回true,我们就不能在HttpResponse上更改任何与Http头(Header)相关的内容了,例如Cookies、Headers、StatusCode等都无法做更改了,否则会抛出异常。

 

结果我发现当上面的代码执行到context.Response.Cookies.Append("DemoCookie", "DemoValue")时,context.Response.HasStarted已经为true了,所以抛出了异常。

因此我将CustomizedMiddleware中间件的代码改为了如下:

using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;

namespace Assembly.Middlewares
{
    public class CustomizedMiddleware
    {
        private readonly RequestDelegate next;

        public CustomizedMiddleware(RequestDelegate next)
        {
            this.next = next;
        }

        public async Task Invoke(Microsoft.AspNetCore.Http.HttpContext context)
        {
            if (!context.Response.HasStarted)//先判断context.Response.HasStarted
            {
                context.Response.Cookies.Append("DemoCookie", "DemoValue");//在next.Invoke(context)前添加Cookie到Response
            }

            //Do something...
            await next.Invoke(context);
            //Do something...
        }
    }
}

这次我把context.Response.Cookies.Append("DemoCookie", "DemoValue")放到了next.Invoke(context)的前面,并做了context.Response.HasStarted的判断,只有当context.Response.HasStarted为false时才添加Cookie,这次就没有抛出异常了,而且context.Response.Cookies.Append("DemoCookie", "DemoValue")也成功添加了Cookie到HttpResponse中。

 

所以这里总结下在ASP.NET Core的中间件中,尽量在next.Invoke(context)调用前做Response.Cookies和Response.Headers等属性的修改,修改前还要判断Response.HasStarted的值,如果是true,就不能做任何修改了。

 

转载于:https://www.cnblogs.com/OpenCoder/p/10343984.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值