WCF service POST method not working - javascript

i am getting following error when i call the wcf service using ajax from another project :
The server encountered an error processing the request. The exception message 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.'. See server logs for more details.
i have created the following wcf service in a project :
IService1.cs -
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json)]
int AddNumbers(int a);
[OperationContract]
string ShowMsg();
// TODO: Add your service operations here
}
service1.cs -
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service1 : IService1
{
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json)]
public int AddNumbers(int a)
{
return a + 5;
}
[WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json)]
public string ShowMsg()
{
return "Hello World!";
}
}
and this is how i am consuming it from another project :
$.ajax({
type: "POST",
url: "http://localhost:16748/Service1.svc/AddNumbers",
contenType: 'application/json',
data: JSON.stringify({ a: 4 }),
dataType: 'json',
success: function (data) {
$("#elementsDiv").html(data);
},
error: function (xhr, status, error) {
var err = xhr.responseText;
$("#elementsDiv").html(err);
}
});
can anybody help me with this?

I believe you may have a typo in your ajax call:
contenType: 'application/json',
I think this should be:
contentType: 'application/json',
other than that your code runs fine for me.

Related

How to httppost a list of objects?

I have this list of objects which I need to send from my angularjs javascript code:
var dataToSend = [{
SubId: "c9cb1d3e-8c32-4a9e-8f0d-0008196776de",
CustomerName: "Blah"
}, {
SubId: "aaaa1d3e-8c32-4a9e-8f0d-0008196776de",
CustomerName: "Blah2"
}]
I've tried these different variations but none of them are working:
1.
$http.post("url",
{
dataType: 'json',
headers: {
contentType: "application/json; charset=utf-8",
},
method: "POST",
data: dataToSend,
}).then...
2.
$http.post("url",
{
data: $.param(dataToSend),
}).then...
3
$http.post("url",
{
data: angular.toJson(dataToSend),
}).then...
4
$http.post("url",
{
data: { customers: dataToSend },
}).then...
5
$http.post("url",
{
data: JSON.stringify({ customers: dataToSend }),
}).then...
My API side code is (I have tried with [FromBody] attribute but no luck there):
[HttpPost]
public async Task<JsonResult> CreateCustomers(List<Customer> customers)
{
// customers is always null
}
And this is my Customer.cs:
public partial class Customer
{
public System.Guid SubId { get; set; }
public string CustomerName { get; set; }
}
Can you please help me? I have tried posting to CreateCustomers(Customer c) without using a list and its working as expected. But when I use a list, its always coming as null on the other side.
EDIT:
$.ajax is working but $http.post isn't. Any idea why?
var request = $.ajax({
dataType: "json",
url: "url",
method: "POST",
data: { '': dataToSend }});
Are you sending JSON ( Include dataType: 'json')
$http({
url: "url",
dataType: 'json',
method: 'POST',
data: dataToSend,
headers: {
contentType: "application/json; charset=utf-8",
}
})
In C# add FromBody in parameter
[HttpPost]
public async Task<JsonResult> CreateCustomers([FromBody]]List<Customer> customers)
{
// customers is always null
}
More on Ajax parameters
contentType is the type of data you're sending, so application/json; charset=utf-8 is a common one, as is application/x-www-form-urlencoded; charset=UTF-8, which is the default.
dataType is what you're expecting back from the server: json, html, text, etc.
This should work. post full code if you face issue
use [ModelBinder] in front of your param.
[HttpPost]
public async Task<JsonResult> CreateCustomers([ModelBinder]List<Customer> customers)
{
// customers is always null
}
Web API only uses model binding for simple types, falling back on formatters for everything else. Adding [ModelBinder] forces the complex types to use model binding anyway.
Your post data is not matched with the parameter List<Customer>.
Change your server side method to something like:
[HttpPost]
public async Task<JsonResult> CreateCustomers(JObject queryParam)
{
// populate your list here
// for eaxample : var customers = queryParam["customers"].ToString();
}
And also you can use this code to send data to the server:
$http({
url: 'url',
dataType: 'json',
method: 'POST',
data: jsonData,
headers: { "Content-Type": "application/json" }
}).success(function(response){ $scope.response = response;
}).error(function(error){ $scope.error = error; });

JQuery trouble with sending ajax report

I am trying to send report with this script:
$(".saveButton").on("click", function(){
var setting = {
'propertyName' : "SomeName",
'propertyValue' : $(this).parent().siblings('.inputCol').children('.inputField').val();
};
$.ajax({
type: "Post",
contentType: "application/json",
url: "/settings/PropertyEdit",
data: JSON.stringify(setting ),
dataType: 'json',
success: function (data) {
//Do something
}
});
And receive my POST in this method:
#Link(label = "Property Edit", family = "SettingsController", parent = "Settings")
#RequestMapping(value = "/settings/PropertyEdit", method = RequestMethod.POST)
public String atmPropertyEdit(Setting setting) {
return "true";
}
However I can even stop into my breakpoint (on return) (Error 403 - no-referrer-when-downgrade), unless I change my request method to GET, then it works fine.
Have tried this script - same 403 error.
$.post('/atmsettings/atmPropertyEdit', { propertyName : "hello", propertyValue : "hello2"},
function(returnedData){
console.log(returnedData);
});

Uncaught SyntaxError: Unexpected token < Ajax call web service

I have a problem with web service web call by js and I need your help.
Thanks
My code service :
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
}
Ajax call service :
function callServices() {
$.ajax({
type: "POST",
url: "WebService.asmx/HelloWorld",
data: "{}",
contentType: "application/jsonp; charset=utf-8",
dataType: "jsonp",
success: function (msg) {
alert(msg.d);
}
});
};
My problem when I pressed F12 to show:
Click to show

Ajax POST 404 Error With asmx

I am attempting to create a webmethod that I can call/POST to from javascript code, but I obtain the following error in console whenever the test() function is called:
"POST http://localhost:53093/TestMethods.asmx/HelloWorld 404 (Not Found)"
I have checked multiple questions similar to mine, but none of the solutions seem to work. Any help would be appreciated.
TestMethods.asmx.cs
[WebService(Namespace = "http://testdomain.com/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[ScriptService]
public class TestMethods : System.Web.Services.WebService
{
[WebMethod()]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string HelloWorld()
{
return "Hello World";
}
}
Javascript (game.js)
function test()
{
$.ajax({
url: "TestMethods.asmx/HelloWorld",
type: 'POST',
data: "{}",
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (result) {
alert(result);
}
});
}
File Structure Image

jQuery Ajax WCF POST - Return Boolean

I can't seem to find an example on how to post from jQuery to a WCF web service and capture the returned boolean. This is the code I have so far for returning JSON data:
Javascript
function VerifyPINData(pin) {
$.ajax({
type: 'POST',
url: "http://localhost:8523/WebService/VerifyPINData?pinData=" + pin,
data: JSON.stringify,
contentType: 'application/json; charset=utf-8',
success: function(data){ alert("result is: " + data); },
error: function() {alert("error"); },
complete: function() { alert("complete"); }
});
}
WCF
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "VerifyPINData?pinData={pinData}")]
bool VerifyPINData(string pinData);
Any help would be appreciated.
Figured it out:
Casted the data returned as a boolean:
success: function(data){ alert("result is: " + Boolean(data)); },
Specified the response as JSON in WCF
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "VerifyPINData?pinData={pinData}", ResponseFormat = WebMessageFormat.Json)]
bool VerifyPINData(string pinData);

Categories