How can I tell when HTTP Headers have been sent in an ASP.NET application?

后端 未结 2 1617
情话喂你
情话喂你 2021-02-19 03:39

Long story short, I have an ASP.NET application I\'m trying to debug and at some point, in very particular circumstances, the application will throw exceptions at a Respon

2条回答
  •  误落风尘
    2021-02-19 03:53

    Samuel's reply just solved this problem for me (+1). I can't paste a code sample in a comment, but in the interest of helping others, here's how I used the event he suggested to add a HeadersWritten property to my IHTTPHandler:

    protected bool HeadersWritten { get; private set; }
    
    void ApplicationInstance_BeginRequest(object sender, EventArgs e)
    {
        HeadersWritten = false;
    }
    
    void ApplicationInstance_PreSendRequestHeaders(object sender, EventArgs e)
    {
        HeadersWritten = true;
    }
    
    public void ProcessRequest(HttpContextBase context)
    {
        context.ApplicationInstance.PreSendRequestHeaders += new EventHandler(ApplicationInstance_PreSendRequestHeaders);
        do_some_stuff();
    }
    

    In my code that would break if I mess with headers too late, I simply check the HeadersWritten property first:

    if (!HeadersWritten)
    {
        Context.Response.StatusDescription = get_custom_description(Context.Response.StatusCode);
    }
    

提交回复
热议问题