获取服务器上的原始HTTP请求

时间:2013-11-11 17:20:04

标签: c# asp.net .net asp.net-mvc http

我希望将HTTP请求作为字符串,而不是解析为HttpRequestBase对象,但是像:

GET /gb/images/v1_3fc5b988.png HTTP/1.1
Host: ssl.gstatic.com
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:25.0) Gecko/20100101 Firefox/25.0
Accept: image/png,image/*;q=0.8,*/*;q=0.5
Accept-Language: ru-RU,ru;q=0.8,en-US;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Referer: https://play.google.com/store/apps/details?id=org.mozilla.firefox&referrer=utm_source%3Dmozilla%26utm_medium%3Dsnippet%26utm_campaign%3Drugoogleplay
Connection: keep-alive

在常规的asp.net mvc3方法中。是否可以或者我应该写出自己的HTTP处理程序?

1 个答案:

答案 0 :(得分:1)

我见过的最接近的是 SaveAs 方法,它保存到磁盘 - 不是一个很好的选择。我确实看过那段代码而且它的确非常符合您的期望。也许基于 SaveAs 的代码, HttpRequestBase 的扩展方法可以吗?

为了节省一些麻烦,这里是 SaveAs 的框架实现:

    public void SaveAs(string filename, bool includeHeaders)
    {
        if (!Path.IsPathRooted(filename) && RuntimeConfig.GetConfig(this._context).HttpRuntime.RequireRootedSaveAsPath)
        {
            object[] objArray = new object[] { filename };
            throw new HttpException(SR.GetString("SaveAs_requires_rooted_path", objArray));
        }
        FileStream fileStream = new FileStream(filename, FileMode.Create);
        try
        {
            if (includeHeaders)
            {
                TextWriter streamWriter = new StreamWriter(fileStream);
                streamWriter.Write(string.Concat(this.HttpMethod, " ", this.Path));
                string queryStringText = this.QueryStringText;
                if (!string.IsNullOrEmpty(queryStringText))
                {
                    streamWriter.Write(string.Concat("?", queryStringText));
                }
                if (this._wr == null)
                {
                    streamWriter.Write("\r\n");
                }
                else
                {
                    streamWriter.Write(string.Concat(" ", this._wr.GetHttpVersion(), "\r\n"));
                    streamWriter.Write(this.CombineAllHeaders(true));
                }
                streamWriter.Write("\r\n");
                streamWriter.Flush();
            }
            ((HttpInputStream)this.InputStream).WriteTo(fileStream);
            fileStream.Flush();
        }
        finally
        {
            fileStream.Close();
        }
    }