simulate ajax call using C# - c#

I am making an ajax call to a local resource like this
$.ajax({
url: 'http://localhost:10001',
dataType: "text",
data: { a: 'aVal',b: 'bVal',message: 'message' },
success: function (data) {
$("#test").append(data);
},
error: function (jqXHR,textStatus,errorThrown) {
alert('error '+textStatus+" "+errorThrown);
}
});
Now i just want to simulate the call from C#.
I am able to make a raw call using this code
WebRequest request = WebRequest.Create("http://localhost:10001");
request.ContentType = "text";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
i dont know how to send the data along.If there is a better way, kindly suggest
Also, I want this to have the exact structure and appearance because i am handling the request at the node js server like this
var url=require('url');
var url_parts=url.parse(request.url,true);
var data=url_parts.query;
Thanks

As it is a get request you can pass parameters in query string of url:
string aVal="aVal";
string bVal="bVal";
string message="message";
string Url ="http://localhost:10001?a="+aVal+"&b="+bVal+"&message="+message;
WebRequest request = WebRequest.Create(url);
For details on How to make get and post Request in C# see this article

Related

Why it works using Ajax POST but not using HttpWebRequest?

Here's a strange thing: I'm trying to send data to a Coldfusion web service via HttpWebRequest (also tried with HttpClient), and I always get a "login page" as response.
BUT, if I do the same thing as Ajax Post, it works.
BUT², if I put the content-type as "application/json" in the Ajax call, it returns the login page as well.
The web service manager says that the service doesn't need login, since we're using VPN to call it. But if I try to access the webservice URI via browser, it opens the login page.
The code in C#:
[EDIT] Created the object using JsonConvert
var request = HttpWebRequest.Create("http://url.cfc");
var obj= new
{
method = "MethodName",
data1 = "123456",
data2 = "aaa"
};
string postData = JsonConvert.SerializeObject(obj);
request.Method = "POST";
//request.ContentType = "application/json"; (not using!!!)
using (var writer = new StreamWriter(request .GetRequestStream()))
{
writer.Write(postData );
writer.Flush();
writer.Close();
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
And the code in JS:
$.ajax({
type: "post",
url: "http://url.cfc",
data: ({
method: "MethodName",
data1: 123456,
data2: "aaa" }),
dataType: "json",
success: function (result) {
console.log(result); },
error: function (result) {
console.log(result); },
});
});
Is there some substantial difference between Ajax call and HttpWebRequest call that can "block" the request using C#? Or maybe I'm failing in put some important data in HttpWebRequest's Header? Moreover: some issue in Coldfusion's web service authorization configuration?
You may need to move the methodname to the url instead of passing as a post param.
In Javascript in your AJAX call:
url: "http://url.cfc?method=MethodName"
and in C#:
var request = HttpWebRequest.Create("http://url.cfc?method=MethodName");

Programmatically making a GET request

Say I had the following Jquery request
$.ajax({
type: "GET",
url: "http://localhost:8501/exampleservice.svc/rest/Start",
contentType: "application/json; charset=utf-8",
processData: false,
data: { confirmationNum : '90210' },
dataType: "json",
success: function (data, status, xhr)
{
},
error: function (xhr, status, error)
{
},
complete: function (xhr, status)
{
}
});
What is the proper way to this correctly in C#?
I have tried the following with an error occurring at the data stream:
"An unhandled exception of type 'System.Net.ProtocolViolationException' "
string biometricURL = "http://localhost:8501/exampleservice.svc/rest/Start";
byte[] jsonData = new ASCIIEncoding().GetBytes("{ confirmationNum : '90210' }");
WebRequest request;
request = WebRequest.Create(biometricURL);
request.ContentType = "application/json; charset=utf-8";
request.ContentLength = jsonData.Length;
request.Credentials = CredentialCache.DefaultCredentials;
Stream dataStream = request.GetRequestStream();
dataStream.Write(jsonData, 0, jsonData.Length);
dataStream.Close();
HttpWebResponse response = (HttpWebResponse)getBiometricCapture.GetResponse();
The GET Request does not have a body / content. As a result, using the:
Stream dataStream = request.GetRequestStream();
dataStream.Write(jsonData, 0, jsonData.Length);
dataStream.Close();
may cause the "System.Net.ProtocolViolationException".
If you want to pass custom data through the GET Request, append custom parameters via the QueryString or Headers.
Otherwise, use the POST Request instead.
The matter here is that you have a body in your GET request. Here are two solutions to solve your issue:
Change your request type to POST instead of GET (type: "POST")
Remove your contentType: "application/json; charset=utf-8" parameter. ContentType is useless if you're doing a GET request. GET requests should not have content-type because they do not have request entity.
As other users have already answered, you don't pass JSON objects in the content body for a GET request. However, using a post method like they suggest is not RESTful, which is what it appears you are trying to build based on the semantics of your example URL.
In RESTful services, simple accessors are implemented with the parameters passed as URL path fragments (the exception generally being complicated queries, in which case you use query variables in the URL or a POST). This is not the case for you, as you are accessing by a simple ID. So, for example, if you are trying to get a BiometricCapture resource with id 12345, you would access the URL:
http://localhost:8501/exampleservice.svc/rest/biocaptures/12345
Included the data as part of the URL like this.
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://localhost:8501/exampleservice.svc/rest/Start?confirmationNum='90210'");
request.Method = "GET";
request.ContentType = "application/json; charset=utf-8";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

POST AJAX request via HTTPHandler to another HTTPHandler

I have a button on a website which sends an AJAX request to a .NET HTTPHandler. In the ProcessRequest method of this handler, it then took the query string parameters, and created a new WebRequest to another URL and appended the parameters onto it.
However, the AJAX request has been changed to use POST rather than GET (amongst other things).
This is what I need to do:
public void ProcessRequest(HttpContext context)
{
// Take POST data from request and create a new request
// with it to another URL
}
What makes it more complicated is that the POST data contains multiple arrays all called 'points' which hold latitude, longitude and altitude. So I can't use context.Request["points"] as that doesn't return an array of my points arrays. And I've tried using context.Request.Form.GetValues("points") but that doesn't seem to work, presumably because the data wasn't submitted as a form.
Edit:
AJAX request is:
$.ajax({
url: self.stationsAllFile,
data: data,
type: 'POST',
success: function (response) {
// store stations as kml string
self.stationsCurrent = response;
self.showStations(self.stationsCurrent, false);
self.listStations(self.stationsCurrent, finishedLoading);
var stations = $.parseXML(response),
$stations = $(stations),
$placemarks = $stations.find('Placemark');
$placemarks.each(function () {
var $placemark = $(this),
latLng = $placemark.find('coordinates').text(),
latLngSplit = latLng.split(','),
lng = latLngSplit[0],
lat = latLngSplit[1];
excludePoints.push(lng + ',' + lat + ',0.000000');
});
// do we need to go again?
if(endPoint < route.length) {
self.processRoute(route, endPoint + 1, excludePoints);
}
},
error: function () {
self.showError(self.language.errors.unknownError);
},
dataType: 'text'
});
Example POST data (pasted from Fiddler):
points%5B%5D=-2.2349300000000003%2C53.48073%2C0.000000&points%5B%5D=-2.26805%2C53.559020000000004%2C0.000000&type=route

how do i turn this $.ajax request into a WebClient execution

I have a page called: tar-url.com
I want to ping target page with a PUT request viai C#.
I want to return a Success or Error to client.
This exists and works with all clients NOT IE.
var xml = "[XMLDOC]";
$.ajax({
type: "PUT",
contentType: "multipart-form",
url: "tar-url.com",
headers: {Authorization: "Basic herpderp="},
data: xml
success: function(){console.log("success");},
error: function(){console.log("error");}
});
This is the request i normally do. It works in my old format, but there is 1 hitch, it doesnt work in IE9, SO i came up with this brilliant idea; Have my server do it, not the browser.
I create a Generic Handler: gHand.ashx which allows me to carry out my calls.
I do this for some other calls, but it is simple GET requests, that return some JSON. Here is where i need help.
I create my method as given in C#:
public void ProcessRequest(HttpContext context)
{
WebClient wsb = new WebClient();
//pass *tar-url.com here*.
string url = context.Request.QueryString["url"];
//pass contentType here.
string ct = context.Request.QueryString["contextType"];
string type = context.Request.QueryString["type"];
string headers = context.Request.QueryString["headers"];
//not sure how to access the xml?
// something like this?
string xml = context.Request.QueryString["save"];
//HERE I NEED TO ASSIGN REST OF STUFF TO *wsg*
string response = wsb.DownloadString(url);
context.Response.Write(response);
}
How i Call it in javascript:
$.ajax({
url:"gHand.ashx",
type: "get",
data: JSON.stringify({
save: xml,
type: "PUT",
url: "tar-url.com",
contentType: "multipart/form",
headers:{ Authorization: "Basic HerpDerp="}
}),
success: function(){...},
error: function(){...}
});
My calls are all seeming to be correct in the sense that i can build a WebClient and execute similar scripts, but it seems that this particular set up boggles my mind.
Edit: Has anyone any idea?
When you send your data to the server, you will want to decode it.
example:
You are sending a map of:
{
save:xml,
url: url,
type:type,
contenType: ct,
headers:{...}
}
So you can look at that and say, similar to how it says:
string url = context.Request.QueryString["url"];
and proceed as normal. Your REQUEST TYPE is the last thing you should check because it determines HOW your WebClient object will react.
Since data is going to be saved, instead of you doing
wsb.DownloadString(url);
which is more or less a get request, you would want to do something like:
wsb.uploadString(URL, METHOD, DATA);
Since you are pushing an XML DOC, or:
wsb.uploadData(URL, METHOD, DATA);
if you are uploading images.
Source: http://msdn.microsoft.com/en-us/library/system.net.webclient.aspx
It doesnt matter which order you assign variables, but when you call uploadData, it is executing the webclient request. There is NOT an wsb.execute() command.

Json object in C# .net

I have a C#.net method as given below
public string jsonTest()
{
List<string> list = new List<string>();
list.Add("aa");
list.Add("bb");
list.Add("cc");
string output = JsonConvert.SerializeObject(list);
return output;
}
Here eventhough Im creating a Json object by using JsonConvert.SerializeObject I am getting a string (since return type is string).
Can I do like below by using a return type JsonResult (or somthing like that) something like what we can do in MVC?
return Json(new { data = list }, JsonRequestBehavior.AllowGet);
Is it possible to create a Json data in asp.net?
In client side I'm using an ajax call to get data from jsonTest().
$.ajax({
type: 'GET',
url: "test.aspx", //In test.aspx pageload calling jsonTest()
dataType: 'json',
success: function (data) {
alert(data);
},
error: function (data) {
alert("In error");
}
});
When I'm giving dataType: 'json', it will go to error part (Since the ajax expects json data but it gets string). Thats why I want to parse it as a json object in server side.
If ASP.NET,
string output = JsonConvert.SerializeObject(list);
Response.Clear();
Response.ContentType = "application/json; charset=utf-8";
Response.Write(output);
Response.End();
There is nothing called a JSON object. The SerializeObject method returns a string because JSON is nothing more than a string value which follows specific rules.
To return JSON to the browser all you need to do is:
Response.ContentType = "application/json; charset=utf-8";
Response.Write(jsonTest());
Response.End();
I'm going to assume you're trying to create a WebMethod for consumption by a JavaScript XHR call or similiar:
ASP.NET will auto-serialize to JSON for POST requests only (using ASMX or so called "Page Methods"). WCF and WebAPI do not require the POST method, but do require some configuration.
[WebMethod]
public static List<Task> TasksGet(string projectId) {
return MyNamespace.Tasks.GetForProject(projectId);
}
The result your JS call sees would be something like:
{"d": [{
"__type": "MyNamespace.Task",
"id": 1,
"description": "This is my first task"
}, {
"__type": "MyNamespace.Task",
"id": 2,
"description": "This is my second task"
}, {
....etc etc
}
]}
No need to mess around w/ the JsonSerializer class directly.
Also make sure your request headers are set correctly:
Content-Accept: application/json;charset=UTF8
Json is just string data. It is how that string is interpreted. So the fact that it is returning a string is correct. You mentioned ASP.Net. Are you using ASP.Net webforms and looking for a way to return that JSON to the front side?

Categories