Convert JavaScript AJAX to HttpWebRequest code

I need imitate AJAX call to web service in my console application. Is there any way to do this with HttpWebRequest?

Source request:

var webRequest = Sys.Net.WebServiceProxy.invoke('http://webserver.com/WS_Message.asmx', 'MyMethod', false, {p1:aa,p2:bb,p3:123}, onSuccess, onFailure, userContext, timeout, enableJsonp, jsonpCallbackParameter);

Sample that doesn't work:

HttpWebRequest request = (HttpWebRequest) WebRequest.Create("http://webserver.com/WS_Message.asmx/MyMethod");
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";

byte[] _bytes= Encoding.UTF8.GetBytes("{p1:aa,p2:bb,p3:123}");

request.ContentLength = _bytes.Length;

Stream stream = request.GetRequestStream();
stream.Write(_bytes, 0, _bytes.Length);
stream.Close();

HttpWebResponse response = (HttpWebResponse) request.GetResponse();

using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
    Console.WriteLine(reader.ReadToEnd());
}

Answers


It looks like you were calling into a (.NET based) web service in javascript. Why not simply add a web reference to your console app, and call it that way ?

It will be much less work than trying to replicate the web service call manually through an HttpWebRequest.


I had to use Chrome Developer Console to see correct http headers. My issue was related to incorrect JSON string format.

@"{""p1"": ""aa"", ""p2"": ""bb"", ""p3"": 123}"


Need Your Help

Webdeploy with WebMatrix and external DB for BlogEngine

webmatrix webdeploy blogengine.net

I do the following : Open Webmatrix and create a new site based on BlogEngine 2.5 from the gallery. This blog tool comes default with a file based XML database.

how to create a filterable list with javascript based on 3 select boxes

php javascript html wordpress

I need to method to implement something similar to what is on this webpage

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.