HttpListener - 如何将WebException HTTP 304“未修改”错误发送回浏览器?

时间:2010-04-09 22:08:13

标签: .net httpwebrequest httpwebresponse httplistener httplistenerrequest

如果我使用HttpListener,如何将WebException 304错误模仿回浏览器?

那就是我收到了对我的HttpListener的请求,然后获得了HttpListenerContext,然后从这一点开始我将如何模仿/安排HTTP“304 Not Modified”响应通过HttpListenerContext有效地发送回浏览器。响应?

编辑:

我尝试了以下操作但是我在尝试将WebException.Status复制到HttpWebResponse.StatusCode时遇到错误(状态代码必须正好是三位数)。关于如何纠正这个问题的任何想法?

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

感谢

1 个答案:

答案 0 :(得分:1)

我想我有:

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