Tuesday, November 21, 2006

Web Service Application proxy for Ajax Cross Domain requests

Calling web services using Ajax (XMLHTTPRequest) should be an easy thing to do, however due to a constraint that inhibits the browser from calling a web service on another machine (for security reasons). See the following article for more details, http://www.xml.com/pub/a/2005/11/09/fixing-ajax-xmlhttprequest-considered-harmful.html.

I submit a C# application proxy like this:
[WebMethod]
public XmlDocument ServiceRequest()
{
System.Web.HttpRequest req = this.Context.Request;
ASCIIEncoding encoding = new ASCIIEncoding();
// The url parameter is the destination web service you are calling
string url = req.Form.Get("url");
string postData = req.Form.ToString();

byte[] buffer = encoding.GetBytes(postData);

HttpWebRequest myRequest = (HttpWebRequest)
WebRequest.Create(url);
myRequest.Method = "POST";
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.ContentLength = buffer.Length;
Stream newStream = myRequest.GetRequestStream();

newStream.Write(buffer, 0, buffer.Length);
newStream.Close();

HttpWebResponse myHttpWebResponse = (HttpWebResponse)myRequest.GetResponse();

Stream streamResponse = myHttpWebResponse.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string strResult = streamRead.ReadToEnd();
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(strResult);
streamRead.Close();
streamResponse.Close();
myHttpWebResponse.Close();
return xmlDoc;

}

Using javascript construct your POST request and pass the destination url and one of the parameters.

1 comment:

Anonymous said...

Can anyone recommend the well-priced Patch Management tool for a small IT service company like mine? Does anyone use Kaseya.com or GFI.com? How do they compare to these guys I found recently: N-able N-central network health tool
? What is your best take in cost vs performance among those three? I need a good advice please... Thanks in advance!

digg / Technology