Cross Domain Access to ashx service using jQuery - asp.net

I have an ASP.NET service that I'm access from a asxh file that returns a JSON string. The service works great except when accessed from our blog sub domain which is on a separate server. (blog.laptopmag.com)
Here is my jQuery
$.ajax({
type: "GET",
url: "http://www.laptopmag.com/scripts/service.ashx",
data: { "op": "get_products" },
dataType: "json",
success: function (data) {
alert(data);
}
});
and here is my ashx file
public class service : IHttpHandler {
public void ProcessRequest (HttpContext context) {
string jsonStr = "{}";
string op = context.Request["op"];
// Process request
context.Response.ContentType = "application/json";
context.Response.Write(jsonStr);
}
public bool IsReusable {
get {
return false;
}
}
}
I've tried switching to a jsonp request, but must be doing something wrong because I can't get anything to pull back. Here is what I've tried.
and here is my jsonp attempt that doesn't seem to work when called from blog.laptopmag.com
$.getJSON('http://www.laptopmag.com/scripts/service.ashx?callback=ProcessRequest&op=get_products', function(json) {
console.log(json);
});

OK, I figured out what the problem was with my JSONP request thanks to the following post:
Jquery success function not firing using JSONP
The problem was that the request wasn't getting a response back in the expected format.
Now, my ashx file now looks like this:
public void ProcessRequest (HttpContext context) {
string jsonStr = "{}";
string op = context.Request["op"];
string jsonp = context.Request["callback"];
// Do something here
if (!String.IsNullOrEmpty(jsonp))
{
jsonStr = jsonp + "(" + jsonStr + ")";
}
context.Response.ContentType = "application/json";
context.Response.Write(jsonStr);
}
and the jQuery ajax request looks like this:
$.getJSON('http://www.laptopmag.com/scripts/service.ashx?callback=?&op=get_products', function(json) {
console.log(json);
});

Security restrictions prevent you from making cross-domain jquery ajax calls, but there are workarounds. IMO the easiest way is to create a page on your site that acts as a proxy and hit the page with your jquery request. In page_load of your proxy:
WebClient client = new WebClient ();
Response.Write (client.DownloadString ("your-webservice-url"));
Other solutions can be found by a quick Google search.

Related

Unity WebGL HTTP Request without IEnumerator or Coroutine

As the title tells I'm trying to make a HTTP Request in Unity (WebGL).
In the documentation I found here: WebGL Networking they tell me to create a IEnumerator type function and call it via a StartCoroutine call.
This is all fine, my problem is that I need to provide a callback HttpRequest to a class that is in another library.
My callback looks like this:
private string HttpRequest(string url, string method, string body=null) {
WWW www = null; // = null is compiler candy
if (method == "GET") {
www = new WWW(url);
} else if (method == "POST") {
//POST specific implementation...
} else {
// do something else
}
while (!www.isDone) { } // this is Wrong.
return www.text;
}
The problem is that unless I return from HttpRequest and the calling method JavaScript won't be able to handle the request. But on the other hand the calling method expects a string not some kind of IEnumerator.
Is there some workaround to let JavaScript do it's work after the WWW class has been constructed?
No
WWW and UnityWebRequest are asynchronous.
To do a synchronous request you need write a javascript plugin. By using some library it's not very complicated, such as jquery.
function getdata($url, $method, $data)
{
var text = '';
$.ajax({
url: $url,
type: $method,
async: false, //synchronous request
data: $data,
success: function(data){
text = data;
},
error: function(data){
text = data;
}
});
return text;
}
More information:
Communication between javascript and unity
jquery.ajax

AJAX call returns page HTML / doesn't hit Page Method is ASP.Net (no MVC or Json)

I am updating a tool for my current company that provides basic product layout documents depending on choices picked. Recently it appears a bot of some sort has been hitting the toolbox periodically, and after some discussion with the company we built the toolbox for we have decided to add the ReCaptcha tool to the page.
The way the toolbox was setup is ASP.net without the use of Json or MVC (the toolbox is a fair few years old, built long before I joined the team). Adding the ReCaptcha tool was not an issue, I did it without a plugin using a window.onload function and using their instructions. This was all done on the options.aspx page, the code for the ReCaptcha call is in the options.aspx.cs page.
To reach this code I am attempting to do an AJAX call where the form would normally be submitted.
The issue: Each AJAX call returns the HTML of the page, and the Page Method (VerifyReCaptcha) does not trigger when I have a break point in it. I need it to call the method which will do all of the listing, then simply pass back a string that simply says if it was a success or not. It doesn't seem to matter what dataType or contentType I enter (if any), or if I run it as POST or GET.
Here is the code of the button that calls the function for the ajax call.
<input type="button" id="DownloadLayoutButton" value="Download Layout" class="navigationButton" style="width: 200px; height: 24px;" />
Here is the function that is called.
$("#DownloadLayoutButton").click(function () {
$.ajax(
{
url: "options.aspx/VerifyReCaptcha",
dataType: "text",
data: {
challenge: Recaptcha.get_challenge(),
response: Recaptcha.get_response()
},
type: "POST",
success: function (result) {
if (result == "Success") {
alert("Success!");
else
alert("ReCaptcha entry was incorrect!");
},
error: function (request, status, error) {
alert("Error!");
}
});
});
This code never seems to hit the VerifyReCaptcha() method that is on the options.aspx.cs page, the method is as follows. As stated I have tested and confirmed that this function works on its own. Previously I had it returning a boolean value but since ajax can't work with booleans, I changed it to return "Success" or "Failure" depending on the result.
[WebMethod]
public static string VerifyReCaptcha(string challenge, string response)
{
try
{
string PRIVATE_KEY = "MY_KEY_HERE";
string remoteip = HttpContext.Current.Request.UserHostAddress;
WebRequest request = WebRequest.Create("http://www.google.com/recaptcha/api/verify");
byte[] dataBytes = System.Text.Encoding.UTF8.GetBytes(String.Format("privatekey={0}&remoteip={1}&challenge={2}&response={3}", PRIVATE_KEY, remoteip, challenge, response));
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = dataBytes.Length;
request.GetRequestStream().Write(dataBytes, 0, dataBytes.Length);
String resultString = String.Empty;
String errorString = String.Empty;
using (StreamReader sr = new StreamReader(request.GetResponse().GetResponseStream()))
{
resultString = sr.ReadLine();
errorString = sr.ReadLine();
}
Boolean b;
b = Boolean.TryParse(resultString, out b) && b;
if (b)
return "Success";
else
return "Failure";
}
catch (Exception)
{
return "Failure";
}
}
The aspx page is using the following sources.
<script type="text/javascript" src="JS/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="JS/jquery-validate/jquery.validate.js"></script>
<script type="text/javascript" src="http://www.google.com/recaptcha/api/js/recaptcha_ajax.js"></script>
Your ASP.NET AJAX Page Method needs to be static.
You have:
public virtual string VerifyReCaptcha()
It needs to be:
public static virtual string VerifyReCaptcha()
Note: Read Why do ASP.NET AJAX page methods have to be static? for more information.
As I understand it, asp.net WebMethods expect posted data in JSON.
In your JavaScript jQuery Ajax call use dataType: "json" rather than dataType: "text".
I also add contentType: "application/json; charset=utf-8" as another option.
The WebMethod is not called if the doesn't find the correctly formatted data it expects.

Strange Behavior when using jQuery/asp.net WebApi

I have 2 Web API Projects:
Api1 is a testing-Environment for the JavaScript Front-End, but has a API
Back-end(the default ValuesController), also for testing.
Api2 is the "true" Back-end, from which the Experimental JavaScript UI schould pull Data. For Testing, i use the default ValuesController here too, because, i want to have the same Output.
Status Quo
The Api1-UI can query the Data from the ValuesController of the own API
The Api2 returns the Correct Data(tested in Firefox and with Fiddler)
The Code
JavaScript Client:
var _load = function (url) {
$.ajax({
url: url,
method: 'GET',
accepts: "application/json; charset=utf-8",
success: function (data) {
alert("Success: " + data);
},
error: function (data) {
alert("Error :" + data);
}
});
};
WebApi Controller method:
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
Problem
The JavaScript UI of the experimental Front-End is not able to display, or even receive, the data from the API 2, which is, according to Fiddler, sent correct.
My first thought was, I am using the wrong Method, but i tried $.getJSON and $.ajax. But i always end up with an error. It just says statusText= "Error"
I don't get, why it can display Data from the own ApiController, but not from the "External"...
Thanks for any Help/Suggestions
You seem to be accessing data from X from a different domain Y using ajax. This seems to be a classic cross domain access issue.
You need to set Access-Control-Allow-Origin to value " * " in your response header.
Response.Headers.Add("Access-Control-Allow-Origin", "*")
There various ways you can solve this
defining this header in IIS
using a actionfilter attribute like below
FilterAttribute
public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
if (actionExecutedContext.Response != null)
actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");
base.OnActionExecuted(actionExecutedContext);
}
}
Using Attribute on Controller Action
[AllowCrossSiteJson]
public Result Get(int id)
{
//return appropriate result
}

Response.Write() in WebService

I want to return JSON data back to the client, in my web service method. One way is to create SoapExtension and use it as attribute on my web method, etc. Another way is to simply add [ScriptService] attribute to the web service, and let .NET framework return the result as {"d": "something"} JSON, back to the user (d here being something out of my control). However, I want to return something like:
{"message": "action was successful!"}
The simplest approach could be writing a web method like:
[WebMethod]
public static void StopSite(int siteId)
{
HttpResponse response = HttpContext.Current.Response;
try
{
// Doing something here
response.Write("{{\"message\": \"action was successful!\"}}");
}
catch (Exception ex)
{
response.StatusCode = 500;
response.Write("{{\"message\": \"action failed!\"}}");
}
}
This way, what I'll get at client is:
{ "message": "action was successful!"} { "d": null}
Which means that ASP.NET is appending its success result to my JSON result. If on the other hand I flush the response after writing the success message, (like response.Flush();), the exception happens that says:
Server cannot clear headers after HTTP headers have been sent.
So, what to do to just get my JSON result, without changing the approach?
This works for me:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void ReturnExactValueFromWebMethod(string AuthCode)
{
string r = "return my exact response without ASP.NET added junk";
HttpContext.Current.Response.BufferOutput = true;
HttpContext.Current.Response.Write(r);
HttpContext.Current.Response.Flush();
}
Why don't you return an object and then in your client you can call as response.d?
I don't know how you are calling your Web Service but I made an example making some assumptions:
I made this example using jquery ajax
function Test(a) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "TestRW.asmx/HelloWorld",
data: "{'id':" + a + "}",
dataType: "json",
success: function (response) {
alert(JSON.stringify(response.d));
}
});
}
And your code could be like this (you need to allow the web service to be called from script first: '[System.Web.Script.Services.ScriptService]'):
[WebMethod]
public object HelloWorld(int id)
{
Dictionary<string, string> dic = new Dictionary<string, string>();
dic.Add("message","success");
return dic;
}
In this example I used dictionary but you could use any object with a field "message" for example.
I'm sorry if I missunderstood what you meant but I don't really understand why you want to do a 'response.write' thing.
Hope I've helped at least. :)

JqueryAjax Webservice and Crossdomain problem

i am having problem with my Jqueryajax call that will consume one of my web service method via cross domain. i have been trying all the possible way to accomplish but still no success. please help me with what i am doing wrong. may be i need to configure web server for some security settings? below is my code. please let me know if you have any question regarding with my code.
//Using Ajax Post
//Webservice will return JSON Format
//Doesn't work in both FF and IE when host to live server , work in local
//Error : Access is denined in xxxx.js in IE
//Http 403 Forbidden in FF , FF request header is OPTION
//this approach is the simplest and best way for me to use
var myID = $("myID").val();
$.ajax({
type: "POST",
url: "http://www.mywebsite.com/webservice/Webservice.asmx/getInfo",
data: "{myID:'"+ myID + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
Dostuff(data);
},
error: FailureCallBack
});
My webservice will look like this
using System.Web.Script.Services;
[WebService(Namespace = "http://www.mywebsite.com/webservice/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class Webservice : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public object getInfo(string myID)
{
//Do stuff here
return getJSONDataFromDataSet(_DS);
}
}
//second Approch <br/>
//Using Ajax GET , webservice will return XML Format <br/>
//Doesn't work in both FF and IE when host to live <br/>
//Error : Access is denined in xxxx.js in IE <br/>
//returning XML data in FF but showing nothing in page <br/>
var myID = $("myID").val();
$.ajax({
type: "GET",
url: "http://www.mywebsite.com/webservice/Webservice.asmx/getInfo?myID="myID"&callback=?",
success: function(data) {
Dostuff(data);
},
error: FailureCallBack
});
Webservice
public SerializableDictionary<string, object> getInfo(string myID)
{
//Do stuff here
SerializableDictionary<string, object> obj = getJSONFromDataTable(_DS);
return obj;
}
//third Approch
//Using normal GET , webservice will return XML Format
//same problem with second approch
var myID = $("myID").val();
var xmlhttprequest = createRequestObject();
var url = 'http://www.mywebsite.com/webservice/Webservice.asmx/getInfo?myID='myID'';
xmlhttprequest.open("GET", url, true);
xmlhttprequest.onreadystatechange = getData;
xmlhttprequest.send(null);
function getData()
{
if ((xmlhttprequest.readyState == 4) &&( xmlhttprequest.status == 200))
{
var myXml = xmlhttprequest.responseXML;
Dostuff(myXml);
}
}
function createRequestObject()
{
if (window.XMLHttpRequest)
{
return xmlhttprequest = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
return xmlhttprequest = new ActiveXObject("Microsoft.XMLHTTP");
}
}
Webservice is same with second approach
EDIT:
now i am getting Access is denied , javascript error for both POST and GET request in IE.
in fiddler i can see Firefox returning the Xml data but nothing showing in page, so i put a alert box in getData
function, myXml variable value is always null, strange i only put 1 alert box and it show alert 3 times.
below is my code
var myID = $("myID").val();
var xmlhttprequest = createRequestObject();
var encodeUrl = escape(_utf8_encode("http://www.mywebsite.com/webservice/Webservice.asmx/getInfo?myID="myID));
var url = 'http://www.mywebsite.com/webservice/proxy.aspx?url='+encodeUrl;
xmlhttprequest.open("GET", url, true); //**ACCESS IS DENIED HERE in this line!!!!**
xmlhttprequest.onreadystatechange = getData;
xmlhttprequest.send(null);
function getData()
{
var myXml = xmlhttprequest.responseXML;
alert(myXml); //ALWAYS NULL and show alert 3 times????
DoStuff(myXml);
}
Please help.
best regards
For security reasons, the ajax requests will not work cross domain. There are two solutions to this.
Make the request to the same server, and use a server based proxy mechanism to then make the request to the other domain.
Use "JSONP", which is an alternative cross way of making ajax like requests. jQuery supports this via the dataType: jsonp rather than json, and there is further explanation via their api docs. This blog entry may be useful - http://bloggingabout.net/blogs/adelkhalil/archive/2009/08/14/cross-domain-jsonp-with-jquery-call-step-by-step-guide.aspx
you will need to create proxy on your domain and pass through the request, explain here: http://www.johnchapman.name/aspnet-proxy-page-cross-domain-requests-from-ajax-and-javascript/
thanks so much for all the reply and help.
i have solved the problem :D
solution is to use JSONP and Javascript dynamic injection to html page.
below is code
HTML
<body>
<script type="text/javascript">
var url = "http://www.mywebsite.com/Javascript/MYJS.js";
var script = document.createElement("script");
script.setAttribute("src",url);
script.setAttribute("type","text/javascript");
document.body.appendChild(script);
</body>
</script>
MYJS.js
var myID = $("#myID").val();
var url = "http://www.mywebsite.com/Webservice.aspx/getInfo?myID="+myID+"";
if (url.indexOf("?") > -1)
url += "&jsonp=" ;
else
url += "?jsonp=" ;
url += "ShowInfoCallback" + "&" ; //Important put ur callback function to capture the JSONP data
url += new Date().getTime().toString(); // prevent caching
var script = document.createElement("script");
script.setAttribute("src",url);
script.setAttribute("type","text/javascript");
document.body.appendChild(script);
function ShowInfoCallback(data)
{
DoWhateverYouWant(data);
}
Webservice.aspx.cs
using System.Web.Script.Serialization;
public partial class Webservice : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(Request.QueryString["myID"]))
this.getInfo();
else
this.getInfoDetails();
}
public void getInfo()
{
string Callback = Request.QueryString["jsonp"];
string encryptedID = Request.QueryString["myID"];
//Dowhateveryouwanthere
object obj = getJSONFromDataTable(myDataSet.Tables[1]);
JavaScriptSerializer oSerializer = new JavaScriptSerializer();
string sJSON = oSerializer.Serialize(obj);
Response.Write(Callback + "( " + sJSON + " );");
Response.End();
}
public void getInfoDetails()
{
//Same as above
//returning 2 tables , Info and InfoDetails
Response.Write(Callback + "( { 'Info' : " + sJSONDetails +",'InfoDetails' : "+ sJSONService + " } );");
Response.End();
}
}
Thanks again

Resources