how to send consecutive messages from httphandler using json,ajax,jquery - asp.net

I am trying to send two consecutive messages from httphandler file to client using JSON,AJAX and JQUERY. Howerver only the second message is displayed . What could be the reson? How do you display both the messages?
.ASHX
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Converters;
public class Gen_BLL : IHttpHandler {
public void ProcessRequest (HttpContext context) {
string ename = JsonConvert.SerializeObject("Message1..");
context.Response.Clear();
context.Response.ContentType = "application/json; charset=utf-8";
context.Response.Write(ename);
ename = JsonConvert.SerializeObject("Message2..");
context.Response.Clear();
context.Response.ContentType = "application/json; charset=utf-8";
context.Response.Write(ename);
}
public bool IsReusable {
get {return false;}
}
}
.JS file:
function funGenAst(usro){
$.ajax({
type: "GET",
url: "Gen_BLL.ashx",
contentType: "application/json; charset=utf-8",
data: { "uso": usro },
dataType: "json",
success: OnComplete,
error: OnFail
});
return false;
}
function OnComplete(result) {
alert(result);
}
function OnFail(result){
alert("fail...');
}
Only one alert is displayed, ie "Message2.." . "Message1.." alert is not popped up at all. How do you get to alert both messages one after the other?
Thanks
bsc

You simple can not do that.
There is a protocol of http communication, and this is break it, from the moment you send some header and some content, there is not prediction to clear the header, and send a second (or new) message.
About Hypertext Transfer Protocol (HTTP): http://www.w3.org/Protocols/rfc2616/rfc2616-sec1.html
Alternative way: Merge your message to one response, or after you receive the first message, make new request to get the second one.

Related

Action page in asp.net

How do i create a page like an action page in php, in C# ?To be specific I only require a page that contains only methods that handle various operations and return result.
How do i solve the above scenario ?
Create a class, then inside the class create your methods to construct the logic behind your application.
Then reference this class with the using keyword in your web pages and use the methods you created wherever you like.
Read about HttpHandlers.
For example, you want to have a method that returns a json string in a web forms application.
Add a new item to your project of type "Generic Handler". This will create a new .ashx file. The main method of any class that implements IHttpHandler is ProcessRequest.
public void ProcessRequest (HttpContext context) {
if(String.IsNullOrEmpty(context.Request["day"]))
{
context.Response.End();
}
string json = "";
byte[] bytes = getByteArray();
json = JsonConvert.SerializeObject(bytes);
context.Response.ContentType = "text/json";
context.Response.Write(json);
}
Change the url in your AJAX call and that should do it. The JavaScript would look like this , where GetFileHandler.ashx is the name of the IHttpHandler you just created:
$.ajax(
{
type: "POST",
async: true,
url: 'Handlers/GetFileHandler.ashx',
data: "Day=" + $.toJSON(day),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
console.log("SUCCESS:" + msg);
},
error: function (msg) {
console.log("error:" + msg);
}
});
Read more here for more details.

WebMethod In Aspx Page Can Not Have access Allow-Origin

I have following code.It is not working for enabling CORS.Please help.I am not able to enable CORS in my Web Method on aspx page :
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.AppendHeader("Access-Control-Allow-Origin", "*");
Response.AppendHeader("access-control-allow-headers", "content-type");
}
[WebMethod]
[ScriptMethod]
public static string Get(string data)
{
System.Web.HttpContext.Current.Response.AppendHeader("Access-Control-Allow-Origin", "*");
System.Web.HttpContext.Current.Response.AppendHeader("access-control-allow-headers", "content-type");
return data + " 123";
}
}
// Java Script
function GetData() {
window.jQuery.support.cors = true;
window.jQuery.ajax({
url: 'http://generalservices.prop.preview.gearhost.com//Default.aspx/Get',
contentType: "application/json; charset=utf-8",
dataType: "json",
type: 'post',
data: "{ data : '12'}",
success: function (d) {
},
error: function (d) {
}
});
error : in Access-Control-Allow-Origin not allowed
Page methods are supposed to be used only from the same page where they are defined.
If you need to fetch data from different pages, I would suggest you look into Asp.Net Web api. Or you could even create a simple Generic handler (.ashx file) which you call from your page(s). The handler could deserialize the Json data, process it and return the required response. In a generic handler you can specify any/all http headers that you need.

ASP.NET - Call Web Service From User Control ( .Ascx ) Returns Error 500 Internal Server Error

so I have some problem. The Problem's Goal is that, when i try to call Web Service from User Control with Ajax, I got 500 Internal Server Error.
There is my code sample:
Web Service .CS
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class BudgetJson : System.Web.Services.WebService {
public BudgetJson ()
{
}
[WebMethod]
public static String GetRecordJson()
{
return " Hello Master, I'm Json Data ";
}
}
User Control ( .Ascx ) File ( Ajax Call )
$(document).ready(function () {
$.ajax({
type: "POST",
url: "BudgetJson.asmx",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg)
{
alert(msg);
}
});
});
So, when page loads and request is sent, I got such response:
soap:ReceiverSystem.Web.Services.Protocols.SoapException: Server was
unable to process request. ---> System.Xml.XmlException: Data at
the root level is invalid. Line 1, position 1. at
System.Xml.XmlTextReaderImpl.Throw(Exception e) at
System.Xml.XmlTextReaderImpl.Throw(String res, String arg) at
System.Xml.XmlTextReaderImpl.ParseRootLevelWhitespace() at
System.Xml.XmlTextReaderImpl.ParseDocumentContent() at
System.Xml.XmlTextReaderImpl.Read() at
System.Xml.XmlTextReader.Read() at
System.Web.Services.Protocols.SoapServerProtocol.SoapEnvelopeReader.Read()
at System.Xml.XmlReader.MoveToContent() at
System.Web.Services.Protocols.SoapServerProtocol.SoapEnvelopeReader.MoveToContent()
at
System.Web.Services.Protocols.SoapServerProtocolHelper.GetRequestElement()
at
System.Web.Services.Protocols.Soap12ServerProtocolHelper.RouteRequest()
at
System.Web.Services.Protocols.SoapServerProtocol.RouteRequest(SoapServerMessage
message) at
System.Web.Services.Protocols.SoapServerProtocol.Initialize() at
System.Web.Services.Protocols.ServerProtocol.SetContext(Type type,
HttpContext context, HttpRequest request, HttpResponse response) at
System.Web.Services.Protocols.ServerProtocolFactory.Create(Type type,
HttpContext context, HttpRequest request, HttpResponse response,
Boolean& abortProcessing) --- End of inner exception stack
trace ---
If i will add method name to url, I got such error:
Unknown web method GetRecordJson. Parameter name: methodName
Description: An unhandled exception occurred during the execution of
the current web request. Please review the stack trace for more
information about the error and where it originated in the code.
Exception Details: System.ArgumentException: Unknown web method
GetRecordJson. Parameter name: methodName
Any Solution ?
A couple things on the server-side:
The method should not be static. That's only the case for "page methods" on ASPX pages.
Second, you need to decorate the service class with the [ScriptService] attribute to be able to communicate with it in JSON, which I'm assuming you probably want to do since you're using jQuery.
[ScriptService]
public class BudgetJson : System.Web.Services.WebService {
[WebMethod]
public String GetRecordJson()
{
return " Hello Master, I'm Json Data ";
}
}
On the client-side, you need to specify which method you want to execute in your $.ajax() URL:
$.ajax({
type: "POST",
url: "BudgetJson.asmx/GetRecordJson",
data: "{}",
// The charset and dataType aren't necessary.
contentType: "application/json",
success: function (msg) {
alert(msg);
}
});
You can also simplify the $.ajax() usage a bit, as shown above. The charset isn't necessary and jQuery automatically detects the dataType from the headers sent back from the server.

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.

Calling ASP.NET web service function via GET method with jQuery

I'm trying to call web service function via GET method using jQuery, but having a problem. This is a web service code:
[WebService(Namespace = "http://something.com/samples")]
[ScriptService]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class TestWebService : System.Web.Services.WebService {
[WebMethod]
public string Test2()
{
string result = null;
try
{
result = "{'result':'success', 'datetime':'" + DateTime.Now.ToString() + "'";
}
catch (Exception ex)
{
result = "Something wrong happened";
}
return result;
}
}
That's the way I call the function:
$.ajax({ type: "GET",
url: "http://localhost/testwebsite/TestWebService.asmx/Test2",
data: "{}",
contentType: "application/json",
dataType: "json",
error: function (xhr, status, error) {
alert(xhr.responseText);
},
success: function (msg) {
alert('Call was successful!');
}
});
Method is called successfully, but result string gets covered by XML tags, like this:
<string>
{'result':'success', 'datetime':'4/26/2010 12:11:18 PM'
</string>
And I get an error because of this (error handler is called). Does anybody know what can be done about this?
Enable ASP.NET ASMX web service for HTTP POST / GET requests
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public string Test2()
{
[...]
}
Rule for json:
You can only access data from the same domain!
The only exception is when using jsonp (which is quite complicated to implement since there is no jsonp serializer in the .NET framework).
If your are using a standard web service (and not WCF) you can find guidance howto implement this here.
Make sure to add this to your ajax options:
contentType: "application/json; charset=utf-8"
Your overall request should look like this to get json back instead of XML:
$.ajax({ type: "GET",
url: "http://localhost/testwebsite/TestWebService.asmx/Test2",
data: "{}",
contentType: "application/json",
dataType: "json",
contentType: "application/json; charset=utf-8".
error: function (xhr, status, error) {
alert(xhr.responseText);
},
success: function (msg) {
alert('Call was successful!');
}
});
ScottGu has a full breakdown on what's required here, but it looks like the missing contentType in your case (that one drove me nuts for a while too).
You might try setting the ResponseFormat on your methods. See http://williamsportwebdeveloper.com/cgi/wp/?p=494 to see how they did it for JSON. It probably just defaults to XML.
You need to decorate the method with the ScriptMethodAttribute:
[WebService(Namespace = "http://something.com/samples")]
[ScriptService]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class TestWebService : System.Web.Services.WebService {
[WebMethod]
[ScriptMethod]
public string Test2()
{
[...]
}
}
This will ensure that the method returns JSON by default (the default value of ResponseFormat is Json).
Did you try WebInvokeAttribute, it has members that define Request & Response formats where you can set to WebMessageFormat.Json.
Something like:
[WebInvoke(UriTemplate = "ServiceName", RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare,
Method = "POST")]
You can use http handler instead of
web service.
You can parse xml response with
javascript on the client.

Resources