.net - HttpListener - 如何将 WebException HTTP 304 "Not Modified"错误发送回浏览器?

标签 .net httpwebrequest httpwebresponse httplistener httplistenerrequest

如果我使用的是 HttpListener,如何模拟 WebException 304 错误返回给浏览器?

那是我收到了对我的 HttpListener 的请求,然后获得了 HttpListenerContext,然后从这一点我将如何模仿/安排 HTTP“304 未修改”响应通过 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();

谢谢

最佳答案

我想我有:

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

关于.net - HttpListener - 如何将 WebException HTTP 304 "Not Modified"错误发送回浏览器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2611264/

相关文章:

c# - 如何在c#中创建一个非矩形窗体?

windows-phone-7 - WP7 中的 HttpWebRequest 超时不适用于计时器

c# - 强制 HttpWebRequest 发送客户端证书

azure - WebRequest.Create 忽略我的循环网络场

c# - HttpWebResponse.ReadTimeout - 不支持超时?

c# - 无法在 RichTextBox 中处理 Ctrl + S

c# - 每个代码页是否作为 .NET 中 System.Text.Encoding 的子类实现

c# - 多线程应用程序

c# - 可以将 catch block 的结果传递给 try block 内的方法吗?

javascript - C# 使用 WebRequest 从脚本获取值