WebMethod In Aspx Page Can Not Have access Allow-Origin - asp.net

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.

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.

how to send consecutive messages from httphandler using json,ajax,jquery

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.

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. :)

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.

Resources