Rahman Nasimi Asl Rahman Nasimi Asl - 29 days ago 16
Ajax Question

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

Answer

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.