简体   繁体   English

C#:HttpWebRequest POST数据不起作用

[英]C#: HttpWebRequest POST data not working

I am developing a C# wpf application that has a functionality of logging into my website and download the file. 我正在开发一个具有登录我的网站并下载文件功能的C#wpf应用程序。 This said website has an Authorize attribute on its action. 该网站在其操作中具有Authorize属性。 I need 2 cookies for me to able to download the file, first cookie is for me to log in, second cookie(which is provided after successful log in) is for me to download the file. 我需要2个cookie才能下载文件,第一个cookie供我登录,第二个cookie(成功登录后提供)供我下载文件。 So i came up with the flow of keeping my cookies after my httpwebrequest/httpwebresponse. 所以我想出了在我的httpwebrequest / httpwebresponse之后保留cookie的流程。 I am looking at my posting flow as maybe it is the problem. 我正在查看我的发布流程,可能是问题所在。 Here is my code. 这是我的代码。

void externalloginanddownload()
{
    string pageSource = string.Empty;
    CookieContainer cookies = new CookieContainer();

    HttpWebRequest getrequest = (HttpWebRequest)WebRequest.Create("login uri");
    getrequest.CookieContainer = cookies;
    getrequest.Method = "GET";
    getrequest.AllowAutoRedirect = false;

    HttpWebResponse getresponse = (HttpWebResponse)getrequest.GetResponse();

    using (StreamReader sr = new StreamReader(getresponse.GetResponseStream()))
    {
        pageSource = sr.ReadToEnd();
    }

    var values = new NameValueCollection
    {
                {"Username", "username"},
                {"Password", "password"},
        { "Remember me?","False"},
            };

    var parameters = new StringBuilder();

    foreach (string key in values.Keys)
    {
        parameters.AppendFormat("{0}={1}&",
            HttpUtility.UrlEncode(key),
            HttpUtility.UrlEncode(values[key]));
    }

    parameters.Length -= 1;

    HttpWebRequest postrequest = (HttpWebRequest)WebRequest.Create("login uri");
    postrequest.CookieContainer = cookies;
    postrequest.Method = "POST";

    using (var writer = new StreamWriter(postrequest.GetRequestStream()))
    {
        writer.Write(parameters.ToString());
    }

    using (WebResponse response = postrequest.GetResponse()) // the error 500 occurs here
    {
        using (var streamReader = new StreamReader(response.GetResponseStream()))
        {
            string html = streamReader.ReadToEnd();

        }
    }
}

When you get the WebResponse, the cookies returned will be in the response, not in the request (oddly enough, even though you need to CookieContainer on the request). 当您获得WebResponse时,返回的cookie将在响应中,而不是在请求中(奇怪的是,即使您需要在请求上使用CookieContainer)。

You will need to add the cookies from the response object to your CookieContainer, so it gets sent on the next request. 您需要将cookie从响应对象添加到CookieContainer,以便在下一个请求时发送它。

One simple way: 一种简单的方法:

for(var cookie in getresponse.Cookies) 
    cookies.Add(cookie)

Since the cookies in response is already a cookies container, you can do this (might help to check for null in case all cookies were already there) 由于响应中的cookie已经是cookie容器,因此您可以执行此操作(如果所有cookie已经存在,可能会帮助检查是否为null)

if (response.Cookies != null) cookies.Add(response.Cookies)

You may also have trouble with your POST as you need to set ContentType and length: 您可能在设置POST时遇到麻烦,因为您需要设置ContentType和长度:

myWebRequest.ContentLength = parameters.Length;
myWebRequest.AllowWriteStreamBuffering = true;

If you have any multibyte characters to think about, you may have to address that as well by setting the encoding to UTF-8 on the request and the stringbuilder, and converting string to bytes and using that length. 如果您要考虑任何多字节字符,则可能还必须解决此问题,方法是在请求和stringbuilder上将编码设置为UTF-8,然后将字符串转换为字节并使用该长度。

Another tip: some web server code chokes if there is no user agent. 另一个提示:如果没有用户代理,则某些Web服务器代码会阻塞。 Try: 尝试:

myWebRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)";

And just in case you have any multibyte characters, it is better to do this: 并且以防万一您有任何多字节字符,最好这样做:

var databytes = System.Text.Encoding.UTF8.GetBytes(parameters.ToString());
myWebRequest.ContentLength = databytes.Length;
myWebRequest.ContentType = "application/x-www-form-urlencoded; charset=utf-8";
using (var stream = myWebRequest.GetRequestStream())
{
    stream.Write(databytes, 0, databytes.Length);
}

In C# Application (Server side Web API) Enable the C++ Exception and Common Language Run time Exceptions using (Ctrl+Alt+E) what is the Server side Exception it's throw. 在C#应用程序(服务器端Web API)中,使用(Ctrl + Alt + E)引发的服务器端异常启用C ++异常和公共语言运行时异常。

First you check data is binding Properly. 首先,您检查数据是否正确绑定。 After you can see what it is Exact Exception. 之后,您可以看到什么是“精确异常”。 the Internal Server Error Mostly throw the data is not correct format and not properly managed Exception. 内部服务器错误多数情况下,抛出的数据格式不正确且管理不当异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM