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.
Related
For some reason I am not able to pass a list of id's into my controller action using my AJAX request. I am getting the below 404 console error. Can anyone tell me why this is happening?
Error
Failed to load resource: the server responded with a status of 404 (Not Found)
http://localhost:8088/Clients/VolDashboard/getViewsAssigned?candidateIds%5B%5D=177
Controller Action
public JsonResult getViewsAssigned(List<long> candidateIds)
{
long clientId = webRequestState.ClientId.Value;
long clientUserId = webRequestState.ClientUserId.Value;
return Json(clientViewService.getViewsAssignedToCandidates(candidateIds, clientId, clientUserId), JsonRequestBehavior.AllowGet);
}
AJAX Request
$.ajax({
type: "GET",
url: "../Clients/VolDashboard/getViewsAssigned?" + $.param({ candidateIds: populateSelectedCandidateIds() }),
success: Success,
error: Errors
});
The problem is that your C# method is expecting a List<long> as the parameter type. According to your url, you're just sending an int (which can be converted to a single long). The problem is that it isn't a collection, so it is unable to find the route. The 404 HTTP code is correct.
In this situation where you're URL encoding the list, your best bet would probably be to pass it as a string.
$.ajax({
type: "GET",
url: "../Clients/VolDashboard/getViewsAssigned?" +
$.param({ candidateIds:
populateSelectedCandidateIds().toString()
}),
success: Success,
error: Errors
});
Then you would need to adjust your C# method like this:
public JsonResult getViewsAssigned(string candidateIds)
{
List<long> idList = candidateIds.Split(',').Select(long.Parse).ToList();
long clientId = webRequestState.ClientId.Value;
long clientUserId = webRequestState.ClientUserId.Value;
return Json(clientViewService.getViewsAssignedToCandidates(idList, clientId, clientUserId), JsonRequestBehavior.AllowGet);
}
Try pass parameters via data property:
var data = populateSelectedCandidateIds();
$.ajax({
type: "GET",
data: {candidateIds: data},
url: "../Clients/VolDashboard/getViewsAssigned",
success: Success,
error: Errors
});
You can also see accepted answer here to get main idea.
I'm trying to post some JSON to a web service. The web-service is executed but there's no data available.
The jQuery looks like this :
var json = {"Results": results};
var jsonArray=JSON.stringify(json);
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: requestURL,
data: jsonArray ,
dataType: "json",
success: function (data) { TCG.QUE.processSaveButtonSucceeded(data); },
error: function (data) { TCG.QUE.processSaveButtonFailed(data); }
});
And the webservice implemented in a controller looks like this :
public HttpResponseMessage Post([FromBody]string value)
{
object o1 = Request.Content;
HttpResponseMessage r = new HttpResponseMessage(HttpStatusCode.OK);
return r;
}
If I take out the [FromBody] directive then I get a 404. If I leave it in the code is executed but the value of the value argument is null.
I thought the [FromBody] directive meant the data was contained in the Request object but if it is I can't find it .
Would appreciate any suggestions so that I can access the JSON from the client within the Post method.
UPDATE:
I just re-read this : http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api which made me wonder whether the name I was giving the JSON blog client side should correspond to the name of the argument on which the [FromBody] is applied so I changed the name of the argument from value to Results but still the value within the Post method is null.
RESOLUTION
After reading the blog post referred to by Prashanth Thurairatnam I changed my method to be like this and it works :
public HttpResponseMessage Post([FromBody]JToken jsonbody)
{
// Process the jsonbody
return new HttpResponseMessage(HttpStatusCode.Created);
}
.
Not sure what you are passing into results. Ran into this blog. You may want to give it a go. The blog talks on passing the data as JSON object/ array (you may want to try without JSON.stringify)
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 simply write out some data to my webpage as a result of a callback. Everything works up until the point where I need to output the result of the callback.
Client-side:
function toServer(data) {
var dataPackage = data + "~";
jQuery('form').each(function () {
document.getElementById('payload').value = JSON.stringify({ sendData: dataPackage });
$.ajax({
type: "POST",
async: true,
url: window.location.href.toString(),
data: jQuery(this).serialize(),
success: function (result) {
//this does not work because it just puts an entire source code copy of my site in there instead...
//document.getElementById('searchResults').value = result
console.log("callback compelete");
},
error: function(error) {
console.log("callback Error");
}
});
});
}
Server-Side: (on page load)
//holds actions from page
string payload = HttpContext.Current.Request.Form["payload"] ?? String.Empty;
// See if there were hidden requests (callbacks)
if (!String.IsNullOrEmpty(payload))
{
string temp_AggregationId = CurrentMode.Aggregation;
string[] temp_AggregationList = temp_AggregationId.Split(' ');
Perform_Aggregation_Search(temp_AggregationList, true, Tracer);
}
else
{
HttpContext.Current.Session["SearchResultsJSON"] = "";
}
The rest of the server-side code works properly and just handles the parsing of the incoming and performs a search of the db and then parses the search results into a JSON obj.
Currently, the only way the json obj gets written to the page is if I call it without the callback (just call it on page load). Also, in firebug, it looks like the entire page source is posting back as the 'result' of the callback. I do see my json result within the posted back 'result' but it also contains the entire page HTML.
Moreover, I can't seem to get the result to post to the page which is the whole point. Actually, I could get the result to post to the page by simply uncommenting that bit in the client side code but it posts a copy of my site and not the actual result I thought I created...
What am I missing? How do you explicitly state in the C# code what is returned to the JS callback as 'result'?
You get the entire page because you're making a request to an ASP.NET page. In fact, you're requesting the vary same page you're viewing. The server is returning what it would return if you were submitting a form.
To get JSON data, you need to create a web method to handle your request. Read this article, it will help you. It shows you how to return simple text, but you can return JSON too. Information on this MSDN article.
Finally, to make sure jQuery is parsing the server response as JSON, change your request and indicate it explicitly:
function toServer(data) {
var dataPackage = data + "~";
jQuery('form').each(function () {
document.getElementById('payload').value = JSON.stringify({ sendData: dataPackage });
$.ajax({
type: "POST",
async: true,
url: window.location.href.toString(),
data: jQuery(this).serialize(),
dataType: 'json',
success: function (result) {
//this does not work because it just puts an entire source code copy of my site in there instead...
//document.getElementById('searchResults').value = result
console.log("callback compelete");
},
error: function(error) {
console.log("callback Error");
}
});
});
}
I want to get data from Webservice( Soap), but it not successfull. My service herehttp://icafe.ipos.vn/WSUitility/evsServiceUtility.svc?wsdl
I use jquery to request to service, code below
var soap = "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
"<soap:Body>" +
"<Test xmlns=''>" +
"</Test>" +
"</soap:Body>" +
"</soap:Envelope>";
$.ajax({
url: 'http://icafe.ipos.vn/WSUitility/evsServiceUtility.svc?wsdl',
method: 'post',
data: soap,
contentType: "text/xml",
dataType: "xml",
beforeSend: function (xhr) {
xhr.setRequestHeader("SOAPAction", "urn:evsServiceUtility/Test1");
},
crossDomain: true,
success: function(SOAPResponse) {
alert('ok');
},
error: function(SOAPResponse) {
alert('no ok');
}
});
And my service:
public string Test()
{
try
{
return "Successfull!";
}
catch (Exception ex)
{
return ex.Message;
}
}
I spended many many times to search and try many solutions but it not working.
Can anyone help me?
I suppose your data type can be XML, not a problem there. Question is, how do you encode your data or parameters? Perhaps check the response in the POST request in the console of your browser.
I picked up a few things in c# to enable this automatically which is nicely documented here:
http://encosia.com/3-mistakes-to-avoid-when-using-jquery-with-aspnet-ajax/
Then one thing left to do was to JSON.stringify() the data. So bhRequest is a json object right?
... and then cross browser you'll have to implement json2.js:
https://github.com/douglascrockford/JSON-js
I don't see where your var named soap is being used. It looks like it should be the "data: " that's being sent to the SOAP service, but there's something called bhRequest there instead.
Also make sure you're allowing Phonegap access to your remote server with
<access subdomains="true" origin="*" />
in your config.xml. When you get things working you can make it more restrictive by limiting it to your icafe.ipos.vn domain.