JSON args are not collected in parameter of POST Method - c#

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

Related

Passing json paramter to wcf rest service post method

I am completely new to WCF world.
I am trying to make POST call to WCF Service method and passing json data to it.
My code snippet is as below:
Ajax POST call:
function PostJSON() {
var form_data = {
"req_limitmsg_header": {
"brch_code": "784",
"rqst_id": "00129538",
"tnx_id": "20150200008695",
"inp_user_id": "UAT01",
"inp_dttm": "20150311183413",
"Func_code": "6010 ",
"idms_tnx_type_code": "N",
"Spaces": "12",
"prod_ref_id": "12"
} ,
"req_limitmsg_detail": [
{
"jrn_exc_cur_code": "0000",
"jrn_exc_act_no": "019000090000",
"sign of exc_acpt_amt": "+",
"exc_acpt_amt": "0000000000000000",
"sign of jrn_exc_amt": "+",
"jrn_exc_amt": "0000000001500000"
},
{
"jrn_exc_cur_code": "0000",
"jrn_exc_act_no": "019000090000",
"sign of exc_acpt_amt": "+",
"exc_acpt_amt": "0000000000000000",
"sign of jrn_exc_amt": "+",
"jrn_exc_amt": "0000000001500000"
}
]
};
$.ajax({
cache: 'false',
async: 'false',
type: 'POST',
url: "http://localhost:10647/JsonTest.svc/Rest/RequestLimitCheckService",
data: JSON.stringify(form_data),
contentType: "application/json; charset=utf-8",
dataType: 'json',
crossDomain: true,
processData: true,
success: function (data, status, jqXHR) {
if(data != null)
{
alert("NOT NULL");
alert(data.toString());
}
else
{
alert("NULL");
alert(data.toString());
alert(status.toString());
}
},
error: function (response) {
alert(response);
}
});
}
WCF Method:
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json,RequestFormat=WebMessageFormat.Json,BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "RequestLimitCheckService")]
public string RequestLimitCheck(string form_data)
{
//do somethig
}
WCF Interface
[OperationContract]
string RequestLimitCheck(string form_data);
What is happening is I am always getting null string. I tried specifying query string parameter style as well but it's of no use. It is only working fine if I specify class to accept the json data.
Please let me know if I am doing anything wrong or missing something.
Remove JSON.stringify(form_data) and use simply form_data instead and try again. Also you do need to specify the type of request format you are expecting.

Not able to call WCF using ajax call

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);
}
});

Adding Cookie in asmx not working

I have a asmx webservice which has a webmethod that I'm calling it via jquery ajax and it returns a string, I want to read and edit cookies from this method, I know that I can read the cookie like this:
HttpContext.Current.Request.Cookie["cookie_name"];
but when I'm trying to change the value of this cookie, this doesn't work:
HttpContext.Current.Response.Cookie["cookie_name"].Value = "some_value";
so let's say this is my function:
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
[WebMethod(EnableSession = true)]
public string myMethod()
{
//...some actions
if(HttpContext.Current.Response.Cookie["cookie_name"] != null)
{
HttpContext.Current.Response.Cookie["cookie_name"].Value = "some_value";
}
return "";
}
and here is my ajax call
$.ajax({
type: "POST",
url: "/route-to/myMethod",
data: JSON.stringify({ }),
contentType: "application/json",
charset: "utf-8",
dataType: "json",
async: true,
cache: false,
success: function (msg) {
}
});
What's exactly is wrong in this code?

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