C#Expect100Continue标头请求

时间:2012-11-20 18:27:15

标签: c# http httpwebrequest webclient httpcookie

我遇到了使用不同域发布用户名和密码的问题 - 一个成功提交表单而另一个没有(表单数据为空)!两个域上的html代码是相同的。以下是示例代码 - 评论域未发布:非常感谢任何帮助!

注意:在nginx上运行的域成功发布数据,而另一个在apache上发布的域不是,如果它与服务器有关

 public class CookieAwareWebClient : System.Net.WebClient
{
    private System.Net.CookieContainer Cookies = new System.Net.CookieContainer();

    protected override System.Net.WebRequest GetWebRequest(Uri address)
    {
        System.Net.WebRequest request = base.GetWebRequest(address);
        if (request is System.Net.HttpWebRequest)
        {
            var hwr = request as System.Net.HttpWebRequest;
            hwr.CookieContainer = Cookies;
        }
        return request;
    }
}

# Main function
NameValueCollection postData = new NameValueCollection();
postData.Add("username", "abcd");
postData.Add("password", "efgh");

var wc = new CookieAwareWebClient();
//string url = "https://abcd.example.com/service/login/";
string url = "https://efgh.example.com/service/login/";

wc.DownloadString(url);

//writer.WriteLine(wc.ResponseHeaders);
Console.WriteLine(wc.ResponseHeaders);

byte[] results = wc.UploadValues(url, postData);
string text = System.Text.Encoding.ASCII.GetString(results);

Console.WriteLine(text);

1 个答案:

答案 0 :(得分:1)

问题在于,每当通过程序发出请求时,会自动添加Expect100Continue标头,这在Apache上处理不当。每次以下列方式发出请求时,您必须将Expect100Continue设置为false。感谢Fiddler领导,虽然我可以通过Amazon EC2实例上的dumpcap工具看到它!这是解决方案!

# Main function
NameValueCollection postData = new NameValueCollection();  
postData.Add("username", "abcd");
postData.Add("password", "efgh");


var wc = new CookieAwareWebClient();
var uri = new Uri("https://abcd.example.com/service/login/");
var servicePoint = ServicePointManager.FindServicePoint(uri);
servicePoint.Expect100Continue = false;

wc.DownloadString(uri);

Console.WriteLine(wc.ResponseHeaders);

byte[] results = wc.UploadValues(uri, postData);
string text = System.Text.Encoding.ASCII.GetString(results);
Console.WriteLine(text);