HttpListener - how do I send a WebException HTTP 304 “Not Modified” error back to browser?

扶醉桌前 提交于 2019-12-01 22:52:55

问题


How do I mimic a WebException 304 error back to browser if I am using HttpListener?

That is I have received a request to my HttpListener, and then obtained the HttpListenerContext, then from this point how would I mimic/arrange for a HTTP "304 Not Modified" response to be effectively sent back to the browser via the HttpListenerContext.response?

EDIT:

I tried the following however I get an error trying to copy WebException.Status to HttpWebResponse.StatusCode (The status code must be exactly three digits). Any ideas on how to correct this?

    catch (WebException ex)
    {
        listenerContext.Response.StatusCode = (int)ex.Status;   //ERROR: The status code must be exactly three digits
        listenerContext.Response.StatusDescription = ex.Message;
        listenerContext.Response.Close();

thanks


回答1:


I think I have it with:

    catch (WebException ex)
    {


        if (ex.Status == WebExceptionStatus.ProtocolError)
        {
            int statusCode = (int) ((HttpWebResponse) ex.Response).StatusCode;
            listenerContext.Response.StatusCode = statusCode;
            listenerContext.Response.StatusDescription = ex.Message;
            log("WARNING", uri, "WebException/ProtocolError: " + ex.GetType() + " - " + ex.Message);
        }
        else
        {
            log("ERROR", uri, "WebException - " + ex.GetType() + " - " + ex.Message);

        }

        listenerContext.Response.Close();
    }


来源:https://stackoverflow.com/questions/2611264/httplistener-how-do-i-send-a-webexception-http-304-not-modified-error-back-t

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!