Not able to call WCF using ajax call - c#

i am new to WCF and have created a WCFand named it as CategoryMasterWCF.svc file with iCategoryMasterWCF.cs having following codes
namespace InfraERP.WebServices
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "ICategoryMasterWCF" in both code and config file together.
[ServiceContract]
public interface ICategoryMasterWCF
{
[OperationContract]
[WebInvoke(ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat= WebMessageFormat.Json)]
string DoWork();
[OperationContract]
[WebGet]
[WebInvoke(ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Json)]
string sting(int id);
}
}
and CategoryMasterWCF.svc.cs having code as follows
namespace InfraERP.WebServices
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "CategoryMasterWCF" in code, svc and config file together.
[AspNetCompatibilityRequirements(RequirementsMode
= AspNetCompatibilityRequirementsMode.Allowed)]
public class CategoryMasterWCF : ICategoryMasterWCF
{
public string DoWork()
{
return "Hello, It Worked! ";
}
public string sting(int id)
{
string _sting = "Number is " +id.ToString();
return _sting;
}
}
}
and then i have added code in my aspx as follows
$.ajax({
type: "POST",
url: '../WebServices/CategoryMasterWCF.svc/sting',
contentType: "application/json; charset=UTF-8; charset-uf8",
data: {id:"1"},
processData: true,
dataType: "json",
success: function (msg) {
alert(msg);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus + "---" + errorThrown);
}
});
The error coming is "unsupported media type".
i am not an expert in WCF or Asp.net. And i have searched a lot in the web and also in stackoverflow, and tested with the changes provided, but found no good result. Currently i have not made any changes in the web config. please help me to find a way out.

Did you try removing contentType and dataType from ajax call?

What's the [WebGet] attribute doing above the sting method? You're supposed to use either one of those (WebGet for Http GET and WebInvoke for the rest with POST as default). Since you're doing a POST request in your website you can remove it.
Also convert the data you are sending to a JSON string:
$.ajax({
type: "POST",
url: '../WebServices/CategoryMasterWCF.svc/sting',
contentType: "application/json; charset=UTF-8; charset-uf8",
data: JSON.stringify({id:"1"}),
processData: true,
dataType: "json",
success: function (msg) {
alert(msg);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus + "---" + errorThrown);
}
});

Related

JSON args are not collected in parameter of POST Method

Following is a contract in IService interface
[OperationContract]
[WebInvoke(UriTemplate = "/service1/Add", ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json,
Method = "POST",
BodyStyle = WebMessageBodyStyle.WrappedRequest)]
MyClass AddProperty(MyClass propertyArgs);
Following is my implementation
public MyClass AddProperty(MyClass args)
{
//I always get args null here
}
Following is my code to call above service
var settings = {
"async": true,
"crossDomain": true,
"url": "url",
"method": "POST",
"headers": {
"content-type": "application/json",
},
"processData": false,
"data": '{"userid": 342507,"name": "markand"}'
}
$.ajax(settings).done(function (response) {
console.log(response);
});
The problem is that my service is enable to collect the data sent from ajax. I get my args parameter always null.
Try this and let me know if it works. I'm using it and it is working fine for me
var data = {"userid": 342507,"name": "markand"};
$.ajax({
contentType: "application/json; charset=utf-8",
data: JSONstring.make(data),
dataType: "json",
type: "POST",
url: "url",
async: true,
timeout: 90000,
success: function (items) {
//Your success handling here
},
error: function (obj, timeout, message) {
//Your error handling here
}
});
Editted: your setting must have only the data to be parsed in this example

Ajax call to WCF return "The incoming message has an unexpected message format 'Raw'. The expected message formats for the operation .."

Using .NET framework 3.5.
I can't figure what's happening? My Get WCF services seem to be fine using the same approach.
Not sure, what's missing?
WCF:
[OperationContract]
[WebInvoke(Method = "POST",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.WrappedRequest)]
public void PutInventory(int caseId, DateTime dateReceived, string tamisCaseNo, string oarNo, string tin, string taxPdr, int oarTypeCd, string idrsOrgAssigned, string idrsTeAssigned, DateTime dateRequestComp, int tasCriteriaCd, string tasExpidateCd, DateTime dateEntered, string remarks)
{
InventoryDAL.PutInventory(caseId, dateReceived, tamisCaseNo, oarNo, tin, taxPdr, oarTypeCd, idrsOrgAssigned, idrsTeAssigned, dateRequestComp, tasCriteriaCd, tasExpidateCd, dateEntered, remarks);
}
Ajax call my webform:
$.ajax({
url: "Services/IVOOARInventoryService.svc/PutInventory",
type: 'POST',
cache: false,
dataType: 'json',
data: ({
caseId: '<%=Request.QueryString["id"]%>', dateReceived: $("#dateEntered").val(), tamisCaseNo: $("#tamisCaseNo").val(), oarNo: $("#OARNo").val(), tin:$("#tin").val(), taxPdr: $("#taxPeriod").val(), oarTypeCd: $("#oarType").val(), idrsOrgAssigned: $("#idrsOrgAssigned").val(), idrsTeAssigned: $("#idrsTeAssigned").val(), dateRequestComp: $("#dateRequestComp").val(), tasCriteriaCd: $("#tasCriteriaComp").val(), tasExpidateCd:$("#tasExpediateCd").val(), dateEntered: $("#dateEntered").val(), remarks: $("#remarks").val()
}),
error: function (jqXHR, textStatus, errorThrown) {
$("div#spinner").fadeOut("slow");
alert(errorThrown);
},
success: function (json) {
$("div#spinner").fadeOut("slow");
}
});
My error:
{"ExceptionDetail":{"HelpLink":null,"InnerException":null,"Message":"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.
Just figured it out, needed to use "JSON.stringify"
Example:
data: JSON.stringify({
caseId: "18"
...etc..
}),
http://encosia.com/asmx-scriptservice-mistake-invalid-json-primitive/
Set the content type to application/json
$.ajax({
url: "Services/IVOOARInventoryService.svc/PutInventory",
type: 'POST',
cache: false,
dataType: 'json',
contentType:"application/json",
data: ({
caseId: '<%=Request.QueryString["id"]%>', dateReceived: $("#dateEntered").val(), tamisCaseNo: $("#tamisCaseNo").val(), oarNo: $("#OARNo").val(), tin:$("#tin").val(), taxPdr: $("#taxPeriod").val(), oarTypeCd: $("#oarType").val(), idrsOrgAssigned: $("#idrsOrgAssigned").val(), idrsTeAssigned: $("#idrsTeAssigned").val(), dateRequestComp: $("#dateRequestComp").val(), tasCriteriaCd: $("#tasCriteriaComp").val(), tasExpidateCd:$("#tasExpediateCd").val(), dateEntered: $("#dateEntered").val(), remarks: $("#remarks").val()
}),
error: function (jqXHR, textStatus, errorThrown) {
$("div#spinner").fadeOut("slow");
alert(errorThrown);
},
success: function (json) {
$("div#spinner").fadeOut("slow");
}
});

always getting null response while calling WCF Rest service with ajax calls

This is probably a very common problem but I couldn't get through it with the solutions from internet . First let me introduce the issue ,
I have a Rest WCF service exposed as follows :
// Service operation that retrieves the KPI result
[OperationContract]
[WebInvoke(Method = "GET", RequestFormat=WebMessageFormat.Json, ResponseFormat=WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "/KPI/{monthYear}/{currentYear}/{companyCode}/{divisionCode}/{shopCode}/{parameterName}/{kpiCode}")]
int Get_SY_KPI(string monthYear,string currentYear,string companyCode, string divisionCode, string shopCode, string parameterName, string kpiCode);
I'm trying to call this service from an html form with a simple ajax call :
$.ajax({
type: "GET",
url: "http://localhost:5547/FoxWcfRest.svc/KPI/March/2014/001/001/003/END_QUANTITY_INDICATOR_HP/002",
contentType: "application/json; charset=utf-8",
success: function(response) {
alert(response);
},
error: function()
{
alert("Oops");
}
});
I'm not sure what's going wrong but I'm getting null alert msg , I've read something about crossdomain issues .. anybody could help ?

400 error using Fiddler to hit a WCF Rest service

Testing with Fiddler and a client test page, I am receiving a 400 error when making an Ajax POST to my WCF service. A GET to the same url works fine though. I set a break point in the C# code on the service, but its not even getting into the method. I need some help determining what is wrong because I have no idea at this point. A similar POST worked fine previously, but I had to rewrite my Ajax call and I'm assuming I'm missing something out of that? Very confused and frustrated.
[OperationContract]
[WebGet(UriTemplate = "/{appName}/{custCode}/{custUserName}/",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare)]
IList<Url> GetUrls(string appName, string custCode, string custUserName);
[OperationContract]
[WebInvoke(BodyStyle = WebMessageBodyStyle.Wrapped,
Method = "POST",
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/{appName}/{custCode}/{custUserName}/")]
ResponseAction SaveDeviceInfo(string appName, string custCode, string custUserName, DeviceInfo deviceInfo);
Here is my Ajax call on the client side:
var jsDeviceInfo = {
deviceUuid: 'Unique660',
deviceModel: 'Mark3',
deviceCordova: '2.3.3',
devicePlatform: 'Android',
deviceVersion: '3.3.0'
};
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "http://localhost:xxx/Service.svc/testApp/custCode/userId",
data: JSON.stringify({ deviceInfo: jsDeviceInfo }),
processdata: false,
success: function (msg) {
alert(msg);
alert('Posted successfully');
},
error: function (msg) {
alert('Failed ' + msg.status);
}
});

Bad call of method

Here is part of my html file:
$('#btnMyButton').click(function () {
alert("message");
ajaxPost("Service1.svc/json/GetMethod", { "humanName": "anna" }, anotherMethod);
});
And here is the method being called:
public Human GetCustomer(string humanName)
{
Human x = new Human();
x.name = humanName;
return x;
}
But I got error - 400 bad request! How to fix it?
The body of the anotherMethod method is:
var txt = JSON.stringify(msg);
log("Result = " + txt);
Here is the name of the method:
[OperationContract]
[WebInvoke(Method = "POST",
ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare)]
Human GetMethod(string humanName);
If you are trying to consume a JSON enabled WCF web service you may try the following:
$('#btnMyButton').click(function () {
$.ajax({
url: 'Service1.svc/json/GetMethod',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({ humanName: 'anna' }),
success: function(result) {
// TODO: do something with the results
}
});
return false;
});
The JSON.stringify method shown here is natively built into modern browsers but if you need to support legacy browsers you might need to include the json2.js script.

Categories