I have a following method in the Controller Api
[HttpPost]
public string TestMethod()
{
var nvc = Request.Form;
return Request.HttpMethod + " | " + string.Join("&", nvc.AllKeys.Select(a => a + "=" + HttpUtility.UrlEncode(nvc[a])));
}
When I do the POST request from the browser, it works properly, but if I try to send the POST using C#, ASP returns 404 error If I remove [HttpPost]
before the method, ASP will tell that i am trying to make a GET request.
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));
I've tried to manipulate with headers, but it was useless. Here's my POST method
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: I send POST request using RESTClient for Firefox; UPD 2: My C# method works for other websites
Aucun commentaire:
Enregistrer un commentaire