How to read XML file on port 80 using HttpHandler - asp.net

How do I read a XML file sent by the client at port 80 using HttpHandler in ASP.NET?

assume the client use the POST method.
<httpHandler>
<add path="1.ashx" verb="post" type="" />
</httpHandler>
the Httphandler code :
public void ProcessRequest(HttpContext context)
{
var stream = context.Request.InputStream;
using (StreamReader sr = new StreamReader(stream))
{
var xml= sr.ReadToEnd(); //json format
XmlDocument.Load(xml)
}
}
the client code using js.
<script type="text/javascript">
$.ajax({
type: 'POST',
url: "1.ashx",
data: { xml:"<xml/>" }
});
</script>

Related

Handle xhr with ASP.NET

I would like to send a POST asynchronously from client side (JavaScript) to server side (ASP.Net) with 2 parameters: numeric and long formated string.
I understand the long formated string must have encodeURIComponent() on it befor passing it.
My trouble is I want to embed the long encoded string in body request and later open it from C# on server side.
Please, can you help me? I'm messing too much with ajax, xhr, Request.QueryString[], Request.Form[], ....
First, create an HTTPHandler:
using System.Web;
public class HelloWorldHandler : IHttpHandler
{
public HelloWorldHandler()
{
}
public void ProcessRequest(HttpContext context)
{
HttpRequest Request = context.Request;
HttpResponse Response = context.Response;
//access the post params here as so:
string id= Request.Params["ID"];
string longString = Request.Params["LongString"];
}
public bool IsReusable
{
// To enable pooling, return true here.
// This keeps the handler in memory.
get { return false; }
}
}
Then register it:
<configuration>
<system.web>
<httpHandlers>
<add verb="*" path="*.ashx"
type="HelloWorldHandler"/>
</httpHandlers>
</system.web>
</configuration>
Now call it - using jQuery Ajax:
$.ajax({
type : "POST",
url : "HelloWorldHandler.ashx",
data : {id: "1" , LongString: "Say Hello"},
success : function(data){
//handle success
}
});
NOTE Totally untested code but it should be very close to what you need.
I just tested and it works out of the box. This is how I called it:
<script language="javascript" type="text/javascript">
function ajax() {
$.ajax({
type: "POST",
url: "HelloWorldHandler.ashx",
data: { id: "1", LongString: "Say Hello" },
success: function (data) {
//handle success
}
});
}
</script>
<input type="button" id="da" onclick="ajax();" value="Click" />

ASP.NET Handler (.ashx) with long Query String Parameters

I want to know what is the best solution for creating ASP.NET HTTP Handler (.ashx) with long Query string parameters, as i have parameter like "description" which will be a long string which will make a problem in URL when access it by HTTP Request.
if you just want use GET method,you can't solved this problem,you can set it at What is the maximum length of a URL? why.
you can change you .ASHX file accept the POST method.
<httpHandler>
<add path="1.ashx" verb="post" type="" />
</httpHandler>
your server-side code like this :
public void ProcessRequest(HttpContext context)
{
var stream = context.Request.InputStream;
using (StreamReader sr = new StreamReader(stream))
{
var text = sr.ReadToEnd();
}
}
or alternative(based on your client-side how to send data)
public void ProcessRequest(HttpContext context)
{
var text= context.Request.Form["text"];
}
your client-side:
<script type="text/javascript">
$.ajax({
type: 'POST',
url: "1.ashx",
data: { name: "John", time: "2pm" }
});
</script>

Cross Domain Access to ashx service using jQuery

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.

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

consume a asp.net web service that returns json from an stand alone html page

I've developed a web service in asp.net and am able to test it from an in-project aspx page and can readily display the information that was returned in JSON format.
I now need to consume the web service from a stand-alone html page.
Does someone have experience with this? I'm puzzled by the part that would replace this
<asp:ScriptManager ID="ScriptManager" runat="server">
<Services>
<asp:ServiceReference Path="~\MyService.asmx" />
</Services>
</asp:ScriptManager>
If this is not possible with straight html and javascript, can someone show me a stand-alone php page that would do it?
See this link:
http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/
Use JQuery
www.jquery.org
Essentially, you make your Web Service script callable, just an attribute in your Web Service definition and you do:
$.ajax({
type: "POST",
url: "~/MyService.asmx/MyMethod",
data: "{parameterName:'" aStringArgument + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
var data = msg.d
// Now var is an object with properties just like your object
}
});
Use JQUery.
You can use Javascript to access your webservice.
For example - if you have a json webservice defined like this:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public String Foo(String p1, String p2)
{
return "Hello World";
}
you could call it as follow:
var httpobj = getXmlHttpRequestObject();
//Gets the browser specific XmlHttpRequest Object
function getXmlHttpRequestObject()
{
if (window.XMLHttpRequest)
return new XMLHttpRequest();
else if(window.ActiveXObject)
return new ActiveXObject("Microsoft.XMLHTTP");
}
CallService()
{
//Set the JSON formatted input params
var param = "{'p1' : 'value1', 'p2' : 'value2'}";
//Send it to webservice
if(httpobj.readyState == 4 || httpobj.readyState == 0)
{
httpobj.open("POST", 'service.asmx/' + 'Foo', true);
//Mark the request as JSON and UTF-8
httpobj.setRequestHeader('Content-Type','application/json; charset=utf-8');
httpobj.onreadystatechange = OnSuccess;
httpobj.send(param);
}
}
//Called on successfull webservice calls
OnSuccess()
{
if (httpobj.readyState == 4)
{
//Retrieve the JSON return param
var response = eval("(" + httpobj.responseText + ")");
}
}
If you do not want to use the ScriptManager (which adds over 100k of JS to your page), you can use this method to use jQuery to connect to your web services.

Resources