V
V
Vlad2018-02-09 13:32:32
C++ / C#
Vlad, 2018-02-09 13:32:32

C# How to correctly pass parameters in a WebRequest POST request?

I'm trying to create a request for an authorization form, if the data is correct - there will be a redirect to another page, if not correct - it will return the authorization form.

WebRequest request = WebRequest.Create("http://www.request.com/");
request.Proxy = new WebProxy(new Uri("http://myproxy.ru"));
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";

NameValueCollection outgoingQueryString = HttpUtility.ParseQueryString(String.Empty);

outgoingQueryString.Add("_method", "POST");
outgoingQueryString.Add("data[User][email]", "[email protected]");
outgoingQueryString.Add("data[User][password]", "QWErty01");

byte[] byteArray = new ASCIIEncoding().GetBytes(outgoingQueryString.ToString());

request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();

dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();

reader.Close();
dataStream.Close();
response.Close();

In responseFromServer I find exactly the authorization form, as if the data is not correct.
At the same time, the same JS request is processed perfectly
$.ajax({
  type: "POST",
  url: 'http://cora-request.com/',
  data: { '_method': 'POST', "data[User][email]": "[email protected]", "data[User][password]": "QWErty01" },
  success: function(response){ console.log(response) }
});

Parameters are passed in the same way
_method=POST&data%5bUser%5d%5bemail%5d=hwac%40my.ru&data%5bUser%5d%5bpassword%5d=QWErty01 -> с#
_method=POST&data%5BUser%5D%5Bemail%5D=hwac%40my.ru&data%5BUser%5D%5Bpassword%5D=QWErty01 -> js

What could be the reason ?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Peter, 2018-02-09
@petermzg

Looking at the jquery documentation , $.ajax defaults to a ContentType of 'application/x-www-form-urlencoded; charset=UTF-8'
Means it is necessary to send data in UTF-8.
Next, you use a NameValueCollection to generate the request body, which does not properly encode special characters.
To correctly create an urlencoded request body, it is better to use the FormUrlEncodedContent class

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question