How enable cors in ajax? - c#

I am trying to call data from the following host url test.domain.com/test2.aspx/BindDatatable, however i keep getting 404 response and the following message in my console window:
error message:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://test.domain.com/test2.aspx. This can be fixed by moving the resource to the same domain or enabling CORS
i have added the following cors header in the web.config file of my host(url ) file:
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="origin" />
<add name="Access-Control-Request-Method" value="POST" />
<add name="Access-Control-Allow-Headers" value="content-type, accept" />
</customHeaders>
</httpProtocol>
</system.webServer>
it also contains the following web-method behind test2.aspx.cs:
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
[WebMethod()]
public static string BindDatatable()
{
DataTable dt = new DataTable();
List<UserDetails> details = new List<UserDetails>();
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["#####"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("######", con))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dtrow in dt.Rows)
{
UserDetails user = new UserDetails();
user.Name= dtrow["###"].ToString();
user.Loan = dtrow["###"].ToString();
user.Evnt = dtrow["###"].ToString();
details.Add(user);
}
}
}
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(details);
}
ajax function called from corsTest.aspx
$(document).ready(function () {
$.support.cors = true;
$.ajax({
type: "Post",
crossDomain: true,
contentType: "application/json; charset=utf-8",
url: "http://wwww.test.domain.com/test2.aspx/BindDatatable",
data: "{}",
dataType: "json",
success: function (data) {
alert(data.toSource());
console.log(data);
var myData = JSON.parse(data.d)
for (var i = 0; i < myData.length; i++) {
$("#tbDetails").append("<tr><td>" + myData[i].Name + "</td><td>" + myData[i].Loan + "</td><td>" + myData[i].Evnt + "</td></tr>");
}
},
error: function (result) {
alert("Error");
}
});
});
I am not sure, what else i am suppose to update further to get this to work. Do I also need, to define the cors header in the head tag of the text2.aspx page as well.
thanks in advance for any further feedback/guide.

I stuck into similar situation today so sharing my solution, hope it could help somebody. I used jsonp to fetch the data from cross domain. Taking your example, if one has access to BindDatatable() method in test2.aspx.cs, then we can modify json object to be returned in the format like jsonData({..your json..}). By wrapping the method with jsonData(), it could be read by jsonp during ajax call made like:
var url = "http://wwww.test.domain.com/test2.aspx/BindDatatable";
$.ajax({
url: url,
dataType: 'jsonp',
jsonpCallback: 'jsonData',
success: function (response) {
console.log('callback success: ', response);
},
error: function (xhr, status, error) {
console.log(status + '; ' + error);
}
});
Otherwise as suggested in the above post, you can create a function in your own application corsTest.aspx.cs and access cross domain link through it in C# and return json as shown below:
$.ajax({
type: "Post",
contentType: "application/json; charset=utf-8",
url: "/corsTest.aspx/BindDatatableTest",
dataType: "json",
.
.
error: function (result) {
alert("Error");
}
});
Define function in corsTest.aspx.cs like:
private string BindDatatableTest()
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
string url = "http://wwww.test.domain.com/test2.aspx/BindDatatable";
WebClient wc = new WebClient();
ServicePointManager.Expect100Continue = false;
ServicePointManager.MaxServicePointIdleTime = 2000;
string json = wc.DownloadString(url);
object jsonData = new
{
jsonFinal = jsonD
};
return Content(serializer.Serialize(jsonData), "application/json");
}
Also, in order to call cross domain url you have to add the following code to web.config:
<system.net>
<settings>
<httpWebRequest useUnsafeHeaderParsing="true" />
</settings>
</system.net>

Check if the remote method is available. Check the firewall of the server where the service is hosted if it allows connections for the specific port. Also check on your machine if output port is not blocked.
Another way to enable cors is to make the connection on the server side.
For instance you can add service reference to the remote method and use that method on the server side in your local project. Then on the client you have to call only the local method that is within your solution and you don't have to enable cors on the client.

Related

JQuery Ajax function not calling backend method in DNN

I cannot get DotNetNuke to execute the backend code from my JQuery Ajax function.
I have the following JQuery code on my View.ascx file
I did try to change the URL to View.ascx/DeleteReviewData but no luck.
function deleteReview(ReviewID){
var ReviewIDToDelete = ReviewID;
$.ajax({
type: "POST",
contentType: "application/json",
url: "https://dnndev.me/Product-View/DeleteReviewData",
data: "{'deleteReviewID': '"+ ReviewIDToDelete +"'}",
datatype: "json",
success: function (data) {
alert("Delete successfull");
},
error: function (error) {
alert(error);
}
});
}
This is my back-end code which doesn't get executed on the View.ascx.cs file:
[System.Web.Services.WebMethod]
public static void DeleteReviewData(int deleteReviewID)
{
try
{
//Deletes a review from the database
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["SiteSqlServer"].ToString()))
{
connection.Open();
using (SqlCommand command = new SqlCommand($"delete from ProductReviews where ReviewID = {deleteReviewID}"))
{
command.Connection = connection;
command.ExecuteNonQuery();
}
connection.Close();
}
}
catch(Exception ex)
{
throw;
}
}
If I should use MapHttpRoute. Does someone have an example, please?
I looked at the following post, but I am not sure about using RouteConfig.cs and extra headers and etc: https://www.dnnsoftware.com/answers/execute-an-action-by-calling-an-ajax-post
I currently get no Console errors. It goes to the success section.
When I hover over Type, ContentType or any one of those while debugging it says not defined. See example below. The site is using JQuery 01.09.01
2nd image
UPDATE
I have changed the URL which now gives me a 404 error: url: $.fn.GetBaseURL() + 'DesktopModules/ProductDetailedView/DeleteReviewData'
I also tried this URL path with adding API API/DeleteReviewData , but I get a [object Object] error as it shows a 404 error in the console.
This is an example:
$.ajax({
data: { "Id": IdToDelete },
type: "POST",
dataType: "json",
url: "/DesktopModules/{API-ProjectName}/API/Main/DeleteExpenseByID"
}).complete(function () {
//...
});
Api method:
[HttpPost]
[DnnAuthorize]
public void DeleteExpenseByID(int Id)
{
//...
}
You need to send a number so you dont need the "'" surrounding ReviewIDToDelete var.
Also check DeleteReviewData for a [POST] attribute, it seems to be a [GET] call.

Parameter can't pass using ajax in Cross Domain

I have used cross domain to call one domain to another as below ,
My ajax call from mvc project as done below,
var tableparameter = '{TableName: "' + $("#tableOneTableName").val() + '" }';
$.ajax({
type: "POST",
url: "http://localhost:55016/api/ajaxapi/onchangetableone",
data: tableparameter,
success: function (response) {
alert("hi");
}
});
Then i added below code in web.config file within web api project as below,
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept,Authorization" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>
Then i written action as below,
[HttpPost]
[Route("api/ajaxapi/onchangetableone")]
public List<DropDownListValuesForQuery> OnChangeTableOne(TableNameFormCustomFilters TableParameter)
{
CaseModel query = new CaseModel();
List<DropDownListValuesForQuery> listValues = new List<DropDownListValuesForQuery>();
listValues = query.GetColumnNames(TableParameter.TableName);
return listValues;
}
And list values as below,
public class TableNameFormCustomFilters
{
public int TableName { get; set; }
}
Here i can access the webapi source using cross domain but the parameter value not come from script. Please give your suggestion.
Thanks in advance.....
change your javascript obj little bit ,
var TableParameter =
{
TableName: $("#tableOneTableName").val()
};
Ajax
$.ajax({
type: "POST",
url: "http://localhost:55016/api/ajaxapi/onchangetableone",
data: TableParameter ,
success: function (response) {
alert("hi");
}
});
' TableParameter ' must be same as model parameter
Check below code :
var TableParameter = { "TableName": $("#tableOneTableName").val() };
$.ajax(
{
url: 'http://localhost:55016/api/ajaxapi/onchangetableone/',
type: "POST",
async: false,
contentType: "application/json;",
data: JSON.stringify(TableParameter),
success: function (result) {
alert("hi");
}
});
Cheers !!

Remove xml tag header from JSON response webService C#

My problem is that I have a webservice on ASP.net, which returns a JSON string object (no XML). But when I call the webmethod I have this:
<string xmlns="https://www.puzzlebooks.com.ar">
{"Tipo":null,"Anio":0,"Mes":null,"CuentaContable":null,"Total":0,"OId":0}
</string>
On client side, the message error is this: Unexpected token < in json at position 0
I expected this JSON:
{"Tipo":null,"Anio":0,"Mes":null,"CuentaContable":null,"Total": 0,"OId": 0}
a pure JSON
This is my web service code:
[WebMethod(EnableSession = true)]
[System.Web.Script.Services.ScriptMethod(ResponseFormat = System.Web.Script.Services.ResponseFormat.Json) ]
public string AcumuladoTotalCompraVenta_MesActual()
{
try
{
ModeloDeClases.Dominio.EstadisticaCompraVenta totalAcumulado = null;
totalAcumulado = RepositorioServicios.RepositoryServices.getInstance().getEstadisticasServices().CompraVenta_TotalAcumuladoDelMesActual(23);
if (totalAcumulado == null)
totalAcumulado = new ModeloDeClases.Dominio.EstadisticaCompraVenta();
string queHAY = new JavaScriptSerializer().Serialize(totalAcumulado);
// return totalAcumulado;
return queHAY;
}
catch (Exception ex)
{
this.Error(ex.Message);
return null;
}
}
And the code from client side (aspx page), is this:
<script type="text/javascript">
$(function ()
{
$.ajax
({
type: "POST",
dataType: "json",
contentType: "application/json",
url: "../webServices/wsEstadisticas.asmx/AcumuladoTotalCompraVenta_MesActual",
data: "{}",
success: chartAcumuladoComprasVentas_MesActual,
error: function (request, status, error)
{
alert('NOP!');
alert(request.statusText);
alert(error);
alert(request.toString());
}
});
})
function chartAcumuladoComprasVentas_MesActual()
{
alert('IT S WORK!');
}
</script>
I search on this site about the same problems, but doesn't work. The library Newtonsoft for JSON don't work for me, because I get the same result when I didn't use it.
Thnaks a lot for everyone
I find my answer here:
asp.net asmx web service returning xml instead of json
this.Context.Response.ContentType = "application/json; charset=utf-8";
this.Context.Response.Write(serial.Serialize(city));

Working example of AJAX file upload to WCF service

I'm looking for an example of an ajax call for streaming data to a WCF service. I am always getting an error.
Any help appreciated, or even links to blogs with a solution.
This is my WCF service class
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class Images : IImages
{
string IImages.UploadImage(string fileKey, Stream imageStream)
{
using (var fileStream = File.Create(#"Images\" + fileKey))
{
imageStream.CopyTo(fileStream);
}
return "done";
}
}
and my contract is
[OperationContract(Name = "UploadImage")]
[WebInvoke(UriTemplate = "?file_key={fileKey}", Method = "POST", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
string UploadImage(string fileKey, Stream imageStream);
I have web.config stream binding
<binding name="PublicStreamBinding"
maxReceivedMessageSize="2000000000" transferMode="Streamed">
<security mode="None" />
</binding>
my ajax client call is like this
var data = '{"image":"' + uri + '"}'
$.ajax({
url: GetServerUrl()+"images.svc/?file_key="+options.fileKey,
type: "POST",
contentType: "application/json",
data: data,
success: function (result) {
console.log("SUCCESS");
},
error: function (jqXHR, textStatus, errorThrown) {
console.log("error in transfer::" + jqXHR.responceText);
}
});
I can't comment on the server-side code, but client-side :
the data variable should be a plain javascript object, not a JSON representation
url shouldn't need the GetServerUrl() prefix; try a leading "/" instead
for a POST request it's more normal to include all parameters in the data object rather than tacking them onto the URL, which is the GET approach. It depends what the server-side code is set up to expect but as far as I can tell, it expects file_key to be in the POST.
You should end up with something like this :
var data = {
image: uri,
file_key: options.fileKey
};
$.ajax({
url: "/images.svc/",//probably
type: "POST",
contentType: "application/json",
data: data,
success: function (result) {
console.log("SUCCESS");
},
error: function (jqXHR, textStatus, errorThrown) {
console.log("errror in transfer::" + jqXHR.responceText);
}
});
Install Fiddler ( www.telerik.com/fiddler ). Launch it. Make the web service call. Click on the record of the call in Fiddler. Click on the 'Raw' tabs for request and response. It will be enlightening and you will see exactly what is passed between server and client. Perhaps some addition WCF troubleshooting data as well in the response.
Also, don't forget to check your Application event log on the machine running the WCF service. You can also add a Global.asax to the WCF project (if its a web project) and put logging code in the Application_Error method. Something like this:
protected void Application_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
if (ex is ThreadAbortException)
{
// Nothing to do here. The thread abended.
}
else
{
activityMgr.Add(System.Reflection.MethodBase.GetCurrentMethod(), ex);
}
}

jQuery Ajax not calling webmethod after url routing

my jquery ajax function is not calling webmethod. jquery function return webservice page's html.
function is not understand "ebulten_add" is a webmethod!
"url:ajaxPage.aspx/e_bulten"
to write webmethod name or not write is same.. both of return ajaxPage.aspx html.
$.ajax({
type: "POST",
url: 'ajaxPage.aspx/ebulten_Add',
data: "{ebEmail:'" + Ebemail + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
$("#span_result").hide();
$("#span_spinner").hide();
$("#span_result").html(result.d).fadeIn();
},
error: function (msg) {
$("#span_result").hide();
$("#span_spinner").hide();
$("#span_result").html("Lütfen tekrar deneyin.").fadeIn();
}
});`
web method in ajaxPage.aspx
[System.Web.Services.WebMethod]
public static string ebulten_Add(string ebEmail)
{
if (ebEmail == "Email")
{
return "*Bilgilerinizi Girmediniz";
}
else
{
List<ListItem> ebList = new List<ListItem>();
ebList.Add(new ListItem("#Eb_email", ebEmail));
BL.Atom.GetByVoid("spEbulten_Add", ebList);
return "*E-Bülten kaydınız başarıyla tamamlanmıştır";
}
}
As I can see, you are returning string not json
so just update your dataType: 'text' and it should be ok
Agree with #SenadM. Either change the dataType:text or return JSON from your webmethod:
[System.Web.Services.WebMethod]
public static string ebulten_Add(string ebEmail)
{
if (ebEmail == "Email")
{
return "{ \"response\": \"*Bilgilerinizi Girmediniz\"}";
}
else
{
List<ListItem> ebList = new List<ListItem>();
ebList.Add(new ListItem("#Eb_email", ebEmail));
BL.Atom.GetByVoid("spEbulten_Add", ebList);
return "{ \"response\": \"*E-Bülten kaydiniz basariyla tamamlanmistir\"}";
}
}
Also, make sure POST is enabled in your web.config:
<configuration>
<system.web>
<webServices>
<protocols>
<!-- <add name="HttpGet"/> --> <!-- uncomment to enable get -->
<add name="HttpPost"/>
</protocols>
</webServices>
</system.web>
</configuration>
Just Change var settings = new FriendlyUrlSettings {AutoRedirectMode = RedirectMode.Permanent}; to var settings = new FriendlyUrlSettings {AutoRedirectMode = RedirectMode.Off}; This should solve the problem.

Categories

Resources