首页 > 解决方案 > ASP.NET POST 接收问题

问题描述

我在控制器中有以下方法Api

[HttpPost]
public string TestMethod()
{
    var nvc = Request.Form;

    return Request.HttpMethod + " | " + string.Join("&", nvc.AllKeys.Select(a => a + "=" + HttpUtility.UrlEncode(nvc[a])));
}

当我从浏览器发出 POST 请求时,它可以正常工作,但如果我尝试使用 C# 发送 POST,ASP 会返回 404 错误如果我[HttpPost]在该方法之前删除,ASP 会告诉我正在尝试发出 GET 请求。

string url = "https://localhost:44300/Api/TestMethod";
        Dictionary<string, string> pars = new Dictionary<string, string>();
pars.Add("a", "b");
pars.Add("c", "d");
pars.Add("e", "f");
Console.WriteLine(POST(url, pars));

我试过用标题来操作,但没用。这是我的 POST 方法

static string POST(string url, Dictionary<string, string> parameters)
{

    HttpWebRequest hwr = (HttpWebRequest)WebRequest.Create(new Uri(url));
    hwr.KeepAlive = false;
    hwr.Method = "POST";
    hwr.ContentType = "application/x-www-form-urlencoded";
    hwr.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:69.0) Gecko/20100101 Firefox/69.0";

    byte[] data = Encoding.UTF8.GetBytes(MakeQueryString(parameters));
    hwr.ContentLength = data.Length;

    using (Stream reqStream = hwr.GetRequestStream())
    {
        reqStream.Write(data, 0, data.Length);
    }

    string result;

    using (HttpWebResponse response = (HttpWebResponse)hwr.GetResponse())
    {
        using (StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8")))
        {
            result = sr.ReadToEnd();
        }
    }

    return result;
}

UPD 1:我使用 RESTClient for Firefox 发送 POST 请求;UPD 2:我的 C# 方法适用于其他网站

REST客户端截图

标签: c#postmodel-view-controller

解决方案


我找到了解决方案。有个问题在web.config

<sessionState timeout="90" cookieless="AutoDetect" />

AutoDetect是否有问题,要解决它,需要删除cookieless="AutoDetect"


推荐阅读