I have an ASP.NET 4.0 WCF service that I am calling using jQuery. I have the service configured to accept a JSON object as a string. Example:
{"name": Joe, "age": 32 }
Everything is working correctly if the JSON string is valid. If the JSON string is not valid I get a 500 Internal Server Error response. What I would like to know is how do I catch the error on the server side so I can handle it myself? I set a breakpoint on the method I am calling and it never gets hit. I am assuming the error is happening when the service is deserializing the string and therefore the object never gets passed as a parameter into my method.
I have looked at the FaultContract attribute and it appears I can return some custom details about the exception but it still doesn't allow me to catch errors at the point it is deserializing the JSON string.
Interface
<ServiceContract()>
Public Interface IApplicationService
<OperationContract()>
<WebInvoke(method:="POST", _
BodyStyle:=WebMessageBodyStyle.WrappedRequest, _
ResponseFormat:=WebMessageFormat.Json,
RequestFormat:=WebMessageFormat.Json)> _
Function DeleteAlbum(albumId As Long) As DeleteAlbumResponse
End Interface
Javascript
var data = JSON.stringify({"albumId" : 53});
$.ajax({
url: '/api/application.svc/Web/DeleteAlbum',
data: data,
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true
})
.done(function (data) {
console.log(data);
})
.fail(function (jqxhr, textStatus, error) {
console.log(error);
});
From your comment, you would like to return a 200 even if the input JSON is invalid.
You would probably be better off handling this by having your WCF method accept any arbitrary data. Once in the method, validate it yourself by serializing/deserializing and then proceeding with your regular logic.
However, to add: By specifying a request format of XML or JSON, it is necessary that the client get it right - this is a best practice and is a good idea to leave the validation to the framework itself. By catering to arbitrary strings, you are creating an 'ambiguous' endpoint which may or may not work depending on the validation logic that you change.
Related
I am new to the web developer side and am trying to make sense of how AJAX headers work. We use .NET Framework MVC project with some methods on the controller that are called by our views to get some data.
Example of our view ajax call to the server:
jQuery.ajax({
type: "POST",
data: { "ElementPath": ElementPath },
dataType: "json",
headers: {
'VerificationToken': forgeryId
},
url: "" + BasePath + "/Home/GetAttributes",
});
The GetAttributes method on the server accepts a string as a parameter and returns a string of JSON objects. When I put a breakpoint on the method, the only thing I see in the string parameter is the contents of ElementPath, and nothing to do with headers. In my mind the server method would also have the contents of forgeryId. So what exactly is using the headers and how?
When I have post the Array of object via API to the server than data is not pass properly to the api.
My object have 2 property one is GUID type and one is string type, at the server side my each object return as null data.
In console posted data is this
posted Params data is this
I am beginner in the reactJs so can any one help me how I can save object or array or any array via API
You may need to use JSON.stringify(dataToPost) in the reactjs to convert the data to string before posting to server. I hope the server is RESTful API
I have make changes in my post method and now my Ajax post method this.
export function postJson(url, data, success, error = nothing) {
const settings = {
url,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
async: true,
success: onSuccess(success, error),
error,
}
if (data) {
settings.data = JSON.stringify(data)
}
$.ajax(settings)
}
$.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.
The webservice code is simple:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void receiveOrder(string json) {
Context.Response.Write("ok");
}
And the jquery calling the webservice is as follows:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: 'http://localhost:50730/GingerWeb.asmx/receiveOrder',
data: 'test', //JSON.stringify(webOrder),
dataType: "text",
success: function(data){
if(data === "ok")
orderPlaced();
}
});
And yet the chrome console reads in provocative red:
500 (Internal Server Error)
The problem is that ASMX web-service need to find all input parameters in the request. If at least one input parameter will be not found in the request to the server the web service failed with the status code 500 (Internal Server Error).
The reason is that you send the data in the wrong way. The name of the input parameter of the web method is json (see void receiveOrder(string json)). So the data option of the $.ajax should be in the form
data: JSON.stringify({json: webOrder})
if you use type: "POST" instead of data: JSON.stringify(webOrder) which you tried before. In the case in the body of the POST request will be json=theVlue instead of just theValue.
If you would use type: "GET" the format of data parameter should be changed to
data: {json: JSON.stringify(webOrder)}
The value of the dataType should be 'json'. After the changes the $.ajax should work.
Moreover I would recommend you to use relative paths in the url option. I mean to use '/GingerWeb.asmx/receiveOrder' instead of 'http://localhost:50730/GingerWeb.asmx/receiveOrder'. It will save you from same origin policy errors.
Hello Oleg: Your explanation is simple and to the point. I had a similar problem which your explanation solved. I am providing code snippet to help 'searchers' understand what I was facing and how the above helped solve. In short I am issuing a simple jquery (.ajax) from a aspx page. I have created a webservice that gets some data from backend (cache/db) and return's the same in json format.
JS CODE:
var parameters = "{'pageName':'" + sPage + "'}"
var request = $.ajax({
type: "POST",
url: "/NotificationWebService.asmx/GetNotification",
data: parameters,
contentType: "application/json; charset=utf-8",
dataType: "json"
});
ASP.NET Code Behind for Web Service
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetNotification(string pageName)
{
JavaScriptSerializer js = new JavaScriptSerializer();
Notification ns = NotificationCache.GetActiveNotificationForPage(pageName);
if (ns != null)
{
NotificationJSData nJSData = new NotificationJSData();
nJSData.Code = ns.Code;
nJSData.displayFreq = (short)ns.DisplayFreq;
nJSData.expiryDate = ns.ToDateStr;
return js.Serialize(nJSData);
}
return null;
}
It is ABSOLUTELY necessary to ensure that you match 'pageName' variable name specified in web service code with what is sent in your data parameter of the ajax request. I had them different and changed it to be the same, after spending hours, I finally found the right solution, thanks to this post. Also, in my case I am only passing a single "name:value" pair so I didn't even have to use some json De-serialization function to get the value, pageName above gives me only the value.
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?