httpclient post方法返回StatusCode:403,ReasonPhrase:“ Forbidden”

时间:2019-06-09 07:26:02

标签: c# post httpclient form-data

我正在尝试使用c#httpclient以编程方式从网站获取数据,但无法获取数据。 我提供了以下链接 https://ngodarpan.gov.in/index.php/home/statewise_ngo/5972/33/1

将有一个以表格格式显示的数据列表,如果单击任何链接,将弹出一个带有全套详细信息的弹出窗口,我需要以编程方式获取每条记录。

>

我每次点击以下链接都尝试生成csrf_token https://ngodarpan.gov.in/index.php/ajaxcontroller/get_csrf

,然后尝试将csrf令牌和ID传递给以下链接 https://ngodarpan.gov.in/index.php/ajaxcontroller/show_ngo_info

但这会引发禁止的错误403。

private void sample1()
{
    string str = 
       "https://ngodarpan.gov.in/index.php/ajaxcontroller/show_ngo_info";
    var client = new HttpClient();

    var pairs = new List<KeyValuePair<string, string>>
    {
        new KeyValuePair<string, string>("id", "169486"),
        new KeyValuePair<string, string>("csrf_cookie_name", 
        "decab99c17a84a9040a03c362317289c")
    };

    var content = new FormUrlEncodedContent(pairs);

    var response = client.PostAsync(str, content).Result;
}

{StatusCode:403,ReasonPhrase:“禁止访问”,版本:1.1,内容:System.Net.Http.StreamContent,标头: {   日期:2019年6月9日,星期日07:01:09 GMT   Set-Cookie:csrf_cookie_name = 2e39ed6c9bb142836d81233ba1a94732; expires =星期日,2019年6月9日07:01:11 GMT;最大年龄= 2;路径= /; httponly   伺服器:Apache / 2.4.6   服务器:(红帽企业版Linux)   服务器:OpenSSL / 1.0.1e-fips   服务器:mod_fcgid / 2.3.9   伺服器:PHP / 5.6.30   伺服器:mod_wsgi / 3.4   伺服器:Python / 2.7.5   X-Powered-By:PHP / 5.6.30   内容长度:1131   内容类型:text / html;字符集= UTF-8 }}

1 个答案:

答案 0 :(得分:0)

当您获得csrf_token时,应将其值设置为两件事。 {strong>请求正文中的csrf_test_name cookies 中的csrf_cookie_name。您可以在浏览器中查看网络标签的详细信息。


private async Task sample1()
{
    var url = "https://ngodarpan.gov.in";
    var uri = new Uri(url);
    string str = $"{url}/index.php/ajaxcontroller/show_ngo_info";
    var csrf_token = "80c719c60ac281c34f2f7720fbd28be9";
    HttpClientHandler handler = new HttpClientHandler();
    handler.CookieContainer = new CookieContainer();
    handler.CookieContainer.Add(uri, new Cookie("csrf_cookie_name",csrf_token)); // Adding a Cookie
    var client = new HttpClient(handler);

    client.DefaultRequestHeaders.Add("X-Requested-With", "XMLHttpRequest");

    var pairs = new List<KeyValuePair<string, string>>
    {
        new KeyValuePair<string, string>("id", "169486"),
        new KeyValuePair<string, string>("csrf_test_name", csrf_token)
    };

    var content = new FormUrlEncodedContent(pairs);

    var response = await client.PostAsync(str, content);
    using (FileStream fS = File.Create("result.json"))
    {
        await response.Content.CopyToAsync(fS);
    }
    Console.WriteLine(response);
}