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.
Related
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
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);
}
});
I am consuming WCF Service Methods from client side using JQuery. I want to save the stream data which is returned from WCF method at client side. Following WCF method is working fine in which I am using our own excelExport's method to create memory stream -
public System.IO.Stream TestExportToExcel()
{
using (_oxBowData = new Data.OxbowDataContext())
{
ExcelExport excelExport = new ExcelExport();
List<SheetData> sheets = new List<SheetData>();
sheets.Add(new SheetData()
{
SheetName = "sheet1",
DataList = _oxBowData.GetLunchReportData(new DateTime(2013, 12, 24)).ToList<object>()
});
using (MemoryStream xlsstream = excelExport.ExportToExcelToStream(sheets))
{
xlsstream.Position = 0L;
return xlsstream;
}
}
}
Service Contract:
[OperationContract]
[WebInvoke(Method = "GET", RequestFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json, UriTemplate = "TestExportToExcel")]
System.IO.Stream TestExportToExcel();
Following is what I am using at Client side but it just returning me error-
$.ajax({
type: "GET",
url: u + "/Terminal/ManagementService.svc/TestExportToExcel",
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: false,
success: function (data) {
alert(JSON.stringify(data));
},
error: function (data) {
alert(JSON.stringify(data));
}
});
When I call this client side ajax call it returns error. Can anybody help?
Actually, the problem is that you are specifying RequestFormat = WebMessageFormat.Json in JSON while your method System.IO.Stream TestExportToExcel() doesn't have any parameter to receive it.
Moreover! .NET enforces you to specify RequestFormat if you are using POST method. So, change your contract like this.
Your Service Contract.
[OperationContract]
[WebInvoke(Method = "POST",
RequestFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "TestExportToExcel")]
System.IO.Stream TestExportToExcel(MyCustomObject jsonRequest);
Ajax:
type: "POST",
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 ?
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);
}
});