Reputation: 4607
I have created an AJAX-enabled WCF service using the following code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Text;
namespace AJAX
{
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class CalculatorService
{
[OperationContract]
[WebInvoke(Method = "GET", BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
public int GetRandomNumber()
{
Random rand = new Random();
return rand.Next(100);
}
[OperationContract]
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
public int Add(int a, int b)
{
return a + b;
}
[OperationContract]
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
public int Subtract(int a, int b)
{
return a - b;
}
}
}
Now, I am trying to make requests to the various methods using the following code:
function random() {
$.ajax
({
type: "GET",
url: "/CalculatorService.svc/GetRandomNumber",
cache: false,
dataType: "json",
success: function (jsonData) {
var number = jsonData.d;
alert(number);
},
error: function (error) {
alert("Error!");
}
});
};
function add() {
var inputData = {"a": 10, "b": 5};
$.ajax
({
type: "POST",
url: "/CalculatorService.svc/Add",
cache: false,
data: JSON.stringify(inputData),
dataType: "json",
success: function (jsonData) {
var number = jsonData.d;
alert(number);
},
error: function (error) {
alert("Error");
}
});
};
function subtract() {
var inputData = { "a": 10, "b": 5 };
$.ajax
({
type: "POST",
url: "/CalculatorService.svc/Subtract",
cache: false,
data: JSON.stringify(inputData),
dataType: "json",
success: function (jsonData) {
var number = jsonData.d;
alert(number);
},
error: function (error) {
alert("Error");
}
});
};
$(document).ready(function () {
$("#randomNumberButton").click(function () {
random();
});
$("#addButton").click(function () {
add();
});
$("#subtractButton").click(function () {
subtract();
});
});
Now, for some strange reason, the GetRandomNumber request works perfectly. However, for the Add and Subtract POST requests, I am getting an "Error 500: Internal Server Error" in the console. How can I solve this problem please? Thanks.
Upvotes: 0
Views: 1655
Reputation: 4607
After adding the following line to each POST ajax request, everything works well.
contentType: "application/json; charset=utf-8",
Upvotes: 1