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();
Related
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");
I have this simple ajax request on the client side:
var name = $("#txtNewsletterName");
var email = $("#txtNewsletterEmail");
$.ajax({
url: "/Handlers/Handler.ashx",
contentType: "application/json; charset=utf-8",
type: "POST",
dataType: "json",
data: {
op: "register_to_newsletter",
name: name.val(),
email: email.val()
},
async: true
});
and this code on the C# server side:
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "application/json";
switch (context.Request["op"])
{
case "register_to_newsletter":
string recipientName = context.Request["name"].Trim();
string recipientEmail = context.Request["email"].Trim();
break;
default:
break;
}
}
The problem is that the data from the request is not passed to the server, so the context.Request["op"], context.Request["name"] and context.Request["email"] are null.
I've also checked context.Request.Form.AllKeys and it's string[0]
So obviously the data does not get to the server.
When checking the Network tab in chrome debugger I see that there are 2 requests sent so I've added a screenshot of the Network data from chrome debugger:
There is a redirect occurring, which seems to be dropping the data.
If you look at the the second screenshot you see a GET HTTP 200, but the data is no longer in the request.
The redirect is from "/Handlers/Handler.ashx" to "/handlers/handler.ashx". Maybe there's an urlrewrite in the web.config that enforces lowercase urls and does a redirect if it matches an uppercase character?
What if you change the url to all lowercase:
url: "/handlers/handler.ashx",
And remove the contentType setting:
contentType: "application/json; charset=utf-8",
Because you're not deserializing the data on the server, but want to send it as the default contentType application/x-www-form-urlencoded; charset=UTF-8.
The dataType is for the response, the contentType for the request.
Try to change the data like:
data: '{"op":"register_to_newsletter","name":"' + name.val() + '","email" :"' + email.val() + '"}'
And also use:
context.Request.Form["op"];
why don't you start working with proper data models?
Instead of using HTTPContext, make your input parameter a model of the data that you want to receive. Then you won't have any issues.
Stringify your object before sending, like this
data: JSON.stringify({
"op": "register_to_newsletter",
"name": name.val(),
"email": email.val()
}),
So the full code should be like this
var name = $("#txtNewsletterName");
var email = $("#txtNewsletterEmail");
$.ajax({
url: "/Handlers/Handler.ashx",
contentType: "application/json; charset=utf-8",
type: "POST",
dataType: "json",
data: JSON.stringify({
"op": "register_to_newsletter",
"name": name.val(),
"email": email.val()
}),
async: true
});
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
I am trying to create a WCF service but I am getting the following error which I have picked up from fiddler when making an Ajax call.
The server encountered an error processing the request. The exception message is 'Error in deserializing body of request message for operation 'GetRecords'. OperationFormatter encountered an invalid Message body. Expected to find an attribute with name 'type' and value 'object'. Found value 'boolean'.'. See server logs for more details. The exception stack trace is:
Could someone explain the error and what could be the cause please as i'm not sure what could be going wrong here.
I am sending an ajax request using POST. Here is my ajax request:
var url = "webservices/mainGrid/Nick.svc/GetRecords"
var source = {
dataType: 'json',
url: url,
type: "POST",
id: "SEQUENCE",
root: 'rowsinfo',
contentType: "application/json; charset=utf-8",
async: false,
cache: false,
columns:[],
datafields:[],
beforeprocessing: function (data) {
var columnsdata = new Array();
var datafieldsdata = new Array();
for (k in data.columnsinfo){
var col={};
col.text = data.columnsinfo[k]["DISPLAYNAME"];
col.datafield = data.columnsinfo[k]["DISPLAYNAME"];
var datafields={};
datafields.name = data.columnsinfo[k]["DISPLAYNAME"];
columnsdata .push(col);
datafieldsdata .push(datafields);
source.columns = columnsdata;
source.datafields = datafieldsdata;
}
$("#jqxgrid").jqxGrid({columns : source.columns});
},
data: {
group: JSON.stringify(checkedGroups),
staff: JSON.stringify(checkedStaff),
MODULE: selectedModuleSEQ
}
};
Any information on the error would be good! thanks
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.