WCF returns 400? - c#

I am trying to create a WCF service but I am getting the following error which I have picked up from fiddler when making an Ajax call.
The server encountered an error processing the request. The exception message is 'Error in deserializing body of request message for operation 'GetRecords'. OperationFormatter encountered an invalid Message body. Expected to find an attribute with name 'type' and value 'object'. Found value 'boolean'.'. See server logs for more details. The exception stack trace is:
Could someone explain the error and what could be the cause please as i'm not sure what could be going wrong here.
I am sending an ajax request using POST. Here is my ajax request:
var url = "webservices/mainGrid/Nick.svc/GetRecords"
var source = {
dataType: 'json',
url: url,
type: "POST",
id: "SEQUENCE",
root: 'rowsinfo',
contentType: "application/json; charset=utf-8",
async: false,
cache: false,
columns:[],
datafields:[],
beforeprocessing: function (data) {
var columnsdata = new Array();
var datafieldsdata = new Array();
for (k in data.columnsinfo){
var col={};
col.text = data.columnsinfo[k]["DISPLAYNAME"];
col.datafield = data.columnsinfo[k]["DISPLAYNAME"];
var datafields={};
datafields.name = data.columnsinfo[k]["DISPLAYNAME"];
columnsdata .push(col);
datafieldsdata .push(datafields);
source.columns = columnsdata;
source.datafields = datafieldsdata;
}
$("#jqxgrid").jqxGrid({columns : source.columns});
},
data: {
group: JSON.stringify(checkedGroups),
staff: JSON.stringify(checkedStaff),
MODULE: selectedModuleSEQ
}
};
Any information on the error would be good! thanks

Related

POST Request Through AJAX In asp.net 5 says Request Entity Too Large ERROR

I have sent the following ajax request:   
var formdata = new FormData($('#form_Id')[0]);
     
$.ajax({
   url: '/DematReport/DP24/ImportFile',
   type: "POST",
   processData: false,
   contentType: false,
   data: formdata,
   timeout: 5000,
   success: function (result) {
}
});
And now I get an error that looks like this:
Is there an upper limit to the amount of data transmitted, or is there a way to circumvent it?

C# - jquery ajax posted params not passing to server

I have this simple ajax request on the client side:
var name = $("#txtNewsletterName");
var email = $("#txtNewsletterEmail");
$.ajax({
url: "/Handlers/Handler.ashx",
contentType: "application/json; charset=utf-8",
type: "POST",
dataType: "json",
data: {
op: "register_to_newsletter",
name: name.val(),
email: email.val()
},
async: true
});
and this code on the C# server side:
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "application/json";
switch (context.Request["op"])
{
case "register_to_newsletter":
string recipientName = context.Request["name"].Trim();
string recipientEmail = context.Request["email"].Trim();
break;
default:
break;
}
}
The problem is that the data from the request is not passed to the server, so the context.Request["op"], context.Request["name"] and context.Request["email"] are null.
I've also checked context.Request.Form.AllKeys and it's string[0]
So obviously the data does not get to the server.
When checking the Network tab in chrome debugger I see that there are 2 requests sent so I've added a screenshot of the Network data from chrome debugger:
There is a redirect occurring, which seems to be dropping the data.
If you look at the the second screenshot you see a GET HTTP 200, but the data is no longer in the request.
The redirect is from "/Handlers/Handler.ashx" to "/handlers/handler.ashx". Maybe there's an urlrewrite in the web.config that enforces lowercase urls and does a redirect if it matches an uppercase character?
What if you change the url to all lowercase:
url: "/handlers/handler.ashx",
And remove the contentType setting:
contentType: "application/json; charset=utf-8",
Because you're not deserializing the data on the server, but want to send it as the default contentType application/x-www-form-urlencoded; charset=UTF-8.
The dataType is for the response, the contentType for the request.
Try to change the data like:
data: '{"op":"register_to_newsletter","name":"' + name.val() + '","email" :"' + email.val() + '"}'
And also use:
context.Request.Form["op"];
why don't you start working with proper data models?
Instead of using HTTPContext, make your input parameter a model of the data that you want to receive. Then you won't have any issues.
Stringify your object before sending, like this
data: JSON.stringify({
"op": "register_to_newsletter",
"name": name.val(),
"email": email.val()
}),
So the full code should be like this
var name = $("#txtNewsletterName");
var email = $("#txtNewsletterEmail");
$.ajax({
url: "/Handlers/Handler.ashx",
contentType: "application/json; charset=utf-8",
type: "POST",
dataType: "json",
data: JSON.stringify({
"op": "register_to_newsletter",
"name": name.val(),
"email": email.val()
}),
async: true
});

Ajax call with a 'failed to load resource : the server responded with a status of 500'

I created a function that do an ajax call but I have this error when I call my GetTempData method in C# :
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
This is my code :
function restoreDatas() {
$.ajax({
url: "/AddRecipe/GetTempData",
type: 'GET',
dataType: 'json',
contentType: 'application/json',
cache: false,
processData: false,
success: function (result) {
}
});
}
The C# method called by the ajax call :
public ActionResult GetTempData()
{
return Json(
new
{
title = Session["title"],
cookingTime = Session["cookingTime"],
preparationTime = Session["preparationTime"],
IngredientList = Session["IngredientList"],
ingredientsDescription = Session["ingredientsDescription"],
nbPersons = Session["nbPersons"],
Category = Session["Category"],
difficulty = Session["difficulty"],
nbStars = Session["nbStars"],
file = Session["file"]
}, JsonRequestBehavior.AllowGet
);
}
I don't see where is the problem ?
Do you have any solutions ?
Thank you
Bring up the developer tools in your browser and take a look at the request / response. For example, in Chrome press F12 to bring up the developer console and head to the Network tab. Try calling your GetTempData method again. You will see an entry in the network tab that corresponds to the GetTempData request and is highlighted in red. If you click on that you will be able to see detailed information about your request and response.
HTH
processData: false,
cache: false,
you ignore these attributes in ajax, if you pass object data to the controller in MVC POST method, at that time you can use these attributes.but in get method is not working, simply you use the get method
thanks

JSON and other parameters in data property of AJAX PUT. ASP.net Web API

I want to send a JSON object and values from text boxes back to my controller, but I am having trouble. I can send just the JSON object successfully, but as soon as I add other parameters I get an error saying the requested resource does not support http method 'PUT'. I have tried commenting out the contentType and using Data: {viewModel: JSON.stringify(jsonData), userName: username}, without any success (I eventually will add more string parameters). Below is my ajax and controller signature. Thanks in advance.
$.ajax({
type: 'PUT',
contentType: 'application/json',
url: 'api/Label',
cache: false,
data: JSON.stringify(jsonData),
success: function (result) {
// TODO
},
error: function (HttpRequest, textStatus, err) {
var response = jQuery.parseJSON(HttpRequest.responseText);
$('#LabelInfo').show();
$('#LabelInfo').text('Error: ' + response.ModelState["viewModel.Pieces"][0]);
}
});
controller signature:
public HttpResponseMessage Put(Label viewModel, string
userName)

JQuery values passed to WebApi is always null

I am having trouble with Web Api and was hoping someone here might be able to help me.
I have a jQuery method as follows ...
function OnInsert(evt) {
var truckId = $("#txtTruckId").val();
var truckReg = $("#txtTruckReg").val();
var description = $("#txtDescription").val();
var condition = $("#txtCondition").val();
var data = '{"obj":{"TruckId":"' + truckId + '","Reg":"' + truckReg +
'","Description":"' + description + '","Condition":"' + condition + '"}}';
var json = JSON.stringify(data)
$.ajax({
url: '/api/Values',
cache: false,
type: 'POST',
data: json,
dataType: 'json',
success: function (results) {
$("#txtTruckId").val('');
$("#txtTruckReg").val('');
$("#txtDescription").val('');
$("#txtCondition").val('');
$.getJSON("api/Values", LoadCustomers);
alert('Truck Added !');
}
})
}
When I debug that the 'data' variable successfully captures the data.
I then have a function in my WebApi controller ...
// POST api/values
public void Post(TruckInfo obj)
{
WebApiTestEntities db = new WebApiTestEntities();
db.TruckInfoes.Add(obj);
db.SaveChanges();
}
However, when I debug thst all of the parameters are showing a null value.
I found this:
http://kennytordeur.blogspot.co.uk/2012/12/web-api-passing-complex-type-in-json.html
Which states I need the following line of code in the Global.asax but that hasn't worked.
ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());
I also found this which kind of comes up with an answer but after trying to alter my code so it looks like the code they have written it still doesn't work.
jQuery posts null instead of JSON to ASP.NET Web API
Is any one able to help?
Thanks in advance
Lex
Start by fixing your JSON:
var data = {
truckId: truckId,
reg: truckReg,
description: description,
condition: condition
};
var json = JSON.stringify(data);
and then make sure you specify the correct content type request header:
$.ajax({
url: '/api/Values',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: json,
success: function (results) {
$("#txtTruckId").val('');
$("#txtTruckReg").val('');
$("#txtDescription").val('');
$("#txtCondition").val('');
$.getJSON("api/Values", LoadCustomers);
alert('Truck Added !');
}
});
I found this:
http://kennytordeur.blogspot.co.uk/2012/12/web-api-passing-complex-type-in-json.html
Which states I need the following line of code in the Global.asax but
that hasn't worked.
No, no, no. Not necessary as long as you format properly your JSON request, the Web API will bind it to your model.

Categories