Ajax call to ASP.NEt Web Api method. Parser error when it is done from HTTPS page - asp.net

$.ajax({
url: "api/basket",
type: "GET",
dataType: "json",
error: function (request, status, error) {
alert(request.responseText);
},
success: function (data) {
Process(data);
}
});
I use ASP.NEN Web forms, .Net Framework 4.0, there is an ajax call above which I make . And when it is done from normal HTTP page it gives me data, But if I make this call being on HTTPS page it returns parserror "Unexpected token <"
What is wrong?

Your ajax request isn't returning JSON, it is returning HTML or XML. Thus, when jQuery attempts to parse the response, the first character is sees is < and it throws the parse error.
Use a debugging tool such as fiddler to see exactly what your request returns.

Related

How to call server api decorated with ValidateAntiForgeryToken using Httpclientfactory Typed clients?

I am trying to incorporate a Edit Form page using GetAsync and PostAsync using typed httpclient. Everything works except my code doesn't call API actions with ValidateAntiForgeryToken. Most of the examples online do not address httpcontent used by httpclientfactory and instead use httpresponse. I am aware that the antiforgery token is missing on my request. How do I attach it to the request header? How do I retrieve it from the view? I want to use as less Javascript as possible. Here's a snippet of my Post request service.
Edit: For what it's worth, my api is dot net core and client is dot net core mvc.
var response = await _httpclient.PostAsync("api/edit/" + id, httpcontent);
response.EnsureSuccessStatusCode(); ```
In the MVC Edit view page, it will use a hidden file (named __RequestVerificationToken) to store the ValidateAntiForgeryToken, you can use F12 developer tools to check it.
<input name="__RequestVerificationToken" type="hidden" value="CfDJ8NrAkS ... s2-m9Yw">
After modifying the data, you could use JQuery to get the updated data, then use JQuery ajax to call the API method with the ValidateAntiForgeryToken. You can refer the sample code in my reply:
if we customize antiforgery options in Startup.ConfigureServices, such as: custom the Header Name for the RequestVerificationToken.
services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN"); //configure the antiforgery service to look for the X-CSRF-TOKEN header. To prevent the cross-site request forgery.
Then, we could use the following script:
$.ajax({
type: "POST",
url: "/Survey/Create",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: { "CategoryName": $("#CategoryName").val(), "CategoryID": $("#CategoryID").val() },
success: function (response) {
alert(response);
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
Besides, you can also refer Prevent Cross-Site Request Forgery (XSRF/CSRF) attacks in ASP.NET Core.

jQuery Ajax Stop is not invoked (No error; 200 OK)

I have a working ASP.Net 2.0 code in my development server that uses jQuery Ajax. The result of the ajax call is used to load dropdown values.
But when this code is deployed to a new DMZ server, the result is not getting populated in dropdown – though I am getting 200 OK as response. One obvious thing is that the Type is different in the response. It is expected as application/json but coming as text/plain.
I have success call back and error callback codes. Along with this I have handlers for ajax start and stop. But none of these events are getting fired. What is the reason error/stop handlers are not getting fired? How can we make it work?
Note: The behavior is same in both IE and Chrome.
Update
Also observed that there is an error logged in console, as shown below. Is it related to the "Type"? How can we address this?
Note: Also note that the Content-Length is 0 in the response headers shown below.
Success Callback
jQuery
function loadASN()
{
var receiveScanParameter = getContainerParameters();
// console.log(receiveScanParameter);
$.ajax({
type: "POST",
url: "rcvScanTXAdd.aspx/GetASNForPlant",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({ receiveScanParameter: receiveScanParameter }),
success: successPopulateASN,
error: errorFunction
});
}
Global jQuery Code
//Global Ajax Error handling Function
function errorFunction(xhr, status, error)
{
if(xhr == 'undefined' || xhr == undefined)
{
alert('xhr undefined');
}
alert(status);
alert(error);
}
$(document).ready(function ()
{
//Ajax Start
$('body').ajaxStart(function()
{
//Change cursor to waiting
$(this).css({'cursor':'wait'})
});
//Ajax End
$('body').ajaxStop(function() {
//Reset the cursor
$(this).css({'cursor':'default'})
});
});
Screenshots
I figured it out.
Step 1: Observed that there is an error logged in browser’s console (saying result is null). [This screenshot is updated in the question]
Step 2: Observed that the content length of the response is zero. Also observed that there is a gzip compression happened on the response (by reading the response headers).
Step 3: Analyzed the server's web.config. It was uisng a C# httpModule for compression. In that httpModule added bypassing logic for json. [I don’t want json to be compressed with this custom module. Later I will consider adding compression to JSON when I use IIS for compression instead of custom module]. Following is the C# code segment for by-passing JSON compression
request.ContentType.ToLower(CultureInfo.InvariantCulture).StartsWith("application/json")
WHen in doubt, read the API docs:
As of jQuery 1.8, the .ajaxStop() method should only be attached to document.
http://api.jquery.com/ajaxStop/
Same note can be found in $.ajaxStart docs

AJAX POST JSON to .NET Webservice gives 500 Internal Server Error

I am trying to consume a .NET webservice with AJAX and want a JSON response. Everything works fine. I have used fiddler and get the appropriate Json returnet. also using the plain URL in the browser gives the appropriate XML.
Even using PHP Curl gives me the right JSON in response but when i am trying to use AJAX i get a "500 Internal Server Error".
Any help appriciated, Thanks.
<script>
$(document).ready(function() {
$.ajax({
type: "POST",
url: "http://localhost:9000/APIs/BuyVoucherService.asmx/HelloWorld",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
alert(data);
},
error: function(data){
alert(data);
}
});
});
</script>
It seems that you have omitted a data definition in your request, try to add something like this:
data: "{}",
The problem i have realized is that this wont work because of cross domian issues. the solution to get the AJAX call to work with a cross domain solution is to use JSONP. http://www.json-p.org/

In ASP.NET with JQuery, how would you define and handle exceptional conditions

I use $.ajax to call a .asmx to get JSON data back. The server side process will meet some exceptional conditions which will give back to client error response for displaying error message.
How would you design the error hanlding mechanism? I mean what would you make server side retrun and let client handle the error?
Thanks.
If it's just an error message (a string), then you can just return that string and set the status to 500 so jQuery recognizes it's not a successful request. Then just use your error handler (or a global .ajaxError() handler for all requests) to do what you want with that message.
For example a simple way to handle all errors like this (instead of per-$.ajax() call) would be:
$(document).ajaxError(function(e, xhr) {
alert("There was an error, server responded with: " + xhr.responseText);
});
ther's an error handler in jquery just like the success function, you need to handle it:
function CallWebService(ParentPage) {
$.ajax({
type: "POST",
url: "../Admission/AdmissionService.asmx/LoadLocations",
data: "{'ParentPage':'" + ParentPage + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$('.innerHospitalCensusdiv').html(data.d);
BindSelectLocation();
},**error: function(ex){
//handle error here
}**
});
}

Problem retrieving XML data from an ASP.NET Web service

I am trying to call a Web service to retrieve some XML data from a database. The Ajax call works fine if I use a static file e.g. like this:
$.ajax({
type: "GET",
url: "test2.xml",
data: buildXMLDataRequestObject(),
dataType: "xml",
success: getXMLDataSucceeded,
error: getXMLDataFailed
});
but fails when I try to call the Web service e.g. like this:
$.ajax({
type: "POST",
url: "Services/CheckOutService.svc/GetXMLData",
data: buildXMLDataRequestObject(),
dataType: "xml",
success: getXMLDataSucceeded,
error: getXMLDataFailed
});
The error I get is:
"The incoming message has an
unexpected message format 'Raw'. The
expected message formats for the
operation are 'Xml', 'Json'. This can
be because a WebContentTypeMapper has
not been configured on the binding.
See the documentation of
WebContentTypeMapper for more
details."
The GetXMLData method looks like this:
// Interface
[OperationContract]
[WebInvoke(ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
string GetXMLData(XMLDataRequest request);
...
// Implementation
public string GetXMLData(XMLDataRequest request)
{
request.ShopperId = ShopperId;
return checkOutManager.GetXMLData(request);
}
The GetXMLData method has been configured to return XML and the Ajax call has its datatype set as XML so I'm very confused as to what is causing the error.
EDIT: If I alter the $.ajax() call slightly so that the contentType is specified I get this error:
The data at the root level is invalid.
Line 1, position 1.
I've tried contentType: "text/xml" and contentType: "application/xml" and both give the same error.
EDIT: Yesterday (Aug 30th) I noticed that the service call would succeed if I omitted the data parameter of the ajax call. I guess there is something about the JSON object that is causing a problem. For now I have implemented this functionality on the server side of the application but I do intend to revisit this when I get some time.
My first guess would be that the content type was wrong. What do you see when you look at the stream using Fiddler or similar?

Resources