WCF Post: Null DataMember Properties - wcf

I am trying to post date to WCF POST method. But the object posted to WCF POST method has no values (null) under any of its property.
Data Contract Class:
[DataContract]
public class NewSession
{
[DataMember]
public int id { get; set; }
[DataMember]
public string title { get; set; }
[DataMember]
public DateTime? date { get; set; }
[DataMember]
public string speaker { get; set; }
}
WCF Post Method:
[OperationContract]
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "/add")]
public string AddSession(NewSession session)
{
//code to add new session
return "success";
}
jquery code to all WCF Post method:
$(".lnk-add").on("click", null, function () {
var session = [{
"id": "3",
"title": "REST 3",
"date": "05/15/2014",
"speaker": "Ron Jacobs"
}];
$.ajax({
url: '/Sessions/add',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(session),
success: function (data, textStatus, jqXHR) {
}
});
});
In debugger, I get null values (check screenshot attached)
What can be possible reason(s) of these null values?
Thanks.

I believe the problem may that you are not indicating that the JSON data contains a NewSession object.
Try this:
var session = [{"NewSession":{
"id": "3",
"title": "REST 3",
"date": "05/15/2014",
"speaker": "Ron Jacobs"
}}];

I think the problem is that you are sending an array of session instead of just a session object.
When I recreate your scenario and use postman to send
{"id": "3","title": "REST 3","date": "\/Date(2014-05-15)\/","speaker": "Ron Jacobs"}
I get the correct values but not if I send:
[{"id": "3","title": "REST 3","date": "\/Date(2014-05-15)\/","speaker": "Ron Jacobs"}]

Related

How to hide a property in a C# class from appearing in the JSON response body of a method that returns IActionResult?

I have defined a ProblemDetails class. I construct an object of this class and return from my Http triggered Azure function upon error.
I have defined a convenience property HasDetail to tell if the object has any detail meaning if the object is empty. However, i don't want this property to be included in the response body. I have applied the [JsonIgnore] attribute as well hoping it will not expose that particular property but i still see this property in the response body. How do i stop this?
Note:
The code and the response are below
I am using system.text.json
Class:
public class ProblemDetails
{
public string Type { get; set; }
public string Title { get; set; }
public int? Status { get; set; }
public string Detail { get; set; }
public string Instance { get; set; }
[JsonIgnore]
public bool HasDetail {
get
{
return !result;
}
}
}
Response body as JSON:
{
"type": "https://aaa/codes",
"title": "Input Not Provided",
"status": 400,
"detail": "Please provide a group name or groupId.",
"instance": "",
"hasDetail": true
}
Azure Function declaration
[OpenApiResponseWithBody(statusCode: HttpStatusCode.OK,
contentType: "application/json",
bodyType: typeof(bool),
Description = "The OK response.")]
[FunctionName(FunctionNames.SomeName)]
public async Task<IActionResult> SomeName(
[HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req)
{
// do something
}

WCF REST Format Output

I have a WCF service using REST protocol.
Code:
[ServiceContract]
public interface IHybridService
{
[OperationContract]
[WebInvoke(Method = "GET", UriTemplate = "/hybridservice/compositedata/{value}", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare)]
CompositeType GetDataUsingDataContract(string value);
}
[DataContract]
public class CompositeType
{
List<Data> data = new List<Data>();
public CompositeType()
{
data.Add(new Data() { Id= 1, Value = "test1" });
}
[DataMember]
public List<Data> DataList
{
get { return data; }
set { data = value; }
}
}
public class Data
{
[DataMember(Name = "DataID")]
public int Id { get; set; }
public string Value { get; set; }
}
Currently it returns the following output:
{
"DataList": [
{
"Id": 1,
"Value": "test1"
}
]
}
How can I change the Id within DataList to DataID? I tried [DataMember(Name = "DataID")] but it doesn't work. I do not want to change the c# property to DataID to make it work.
Found the reason, I had to declare Data class as [DataContract].

Model binding not working for List<T> T in case of Web api 2

I have a action method with HTTP Verb: POST which accepts List<Student> student object from body as one of the input parameter of the action method:
[Route("{Id:int}/save", Name = "SaveStudent")]
[HttpPost]
public IHttpActionResult AddStudent(int Id,[FromBody]List<Student> students)
{
return Ok<List<Student>>(students);
}
Now when I tried to test the above method from the Fiddler using the below request details:
{
"students": [
{
"name": "Test",
"rollno": null,
"totalmarks": null
}
]
}
I am getting a 400 bad request error.
Can anyone help me to know what exactly I am missing here?
array is not in correct format it should be like this:
[{name: "Test", rollno: null, totalmarks: null }, {name: "Test2", rollno: null, totalmarks: null }]
Model class used in C#
public class Student {
public string Name { get; set; }
public int RollNo { get; set; }
public int TotalMarks { get; set; }
}
Additional json format resolver added during webapi initialization.
config.MapHttpAttributeRoutes();
var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
I hope this will help you getting this working now

How to set a method with class as a parameter in WCF service?

I am trying to create a method with class as a parameter. But it's throwing error. After some search I found the implementation of QueryStringConverter.
I am trying to do it but I didn't have much knowledge in it.
In my service class, the method is :
[WebInvoke(UriTemplate="LogInForMobileWithDeviceNo", Method="POST", RequestFormat=WebMessageFormat.Json, ResponseFormat=WebMessageFormat.Json, BodyStyle=WebMessageBodyStyle.Wrapped)]
string LogInForMobileWithDeviceNo(clsUserDeviceInfo userDeviceInfo);
In the clsUserDeviceInfo class, i declared the properties as:
[DataContract]
public class clsUserDeviceInfo
{
[DataMember]
public string UserID{get;set;}
[DataMember]
public string DeviceName{get;set;}
[DataMember]
public string CordovaVersion{get;set;}
[DataMember]
public string DevicePlatformJs{get;set;}
[DataMember]
public string DeviceUID{get;set;}
[DataMember]
public string DeviceModel { get; set; }
[DataMember]
public string DeviceVersion { get; set; }
}
but it's not working.
using Jquery i did Ajax posting:
var DeviceName = "samsung";
var CordovaVersion = "2.1.1.1";
var DevicePlatformJs = "windows 8";
var DeviceUID = "23dswd-234dff-23-2334nhj";
var DeviceModel = "grand duos";
var DeviceVersion = "3.2";
var DataArr = {DeviceName:DeviceName,CordovaVersion:CordovaVersion, DevicePlatformJs:DevicePlatformJs,DeviceUID:DeviceUID,DeviceModel:DeviceModel,DeviceVersion:DeviceVersion};
$.ajax({
type: "GET",
url: serverurl,
data: JSON.stringify(DataArr),
success: function (result) {
alert(result);
},
accept: 'application/json'
});
Am I doing anything wrong?
Do you have a OperationContract, this should work!
[OperationContract]
[WebGet(BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json, UriTemplate = "/LogInForMobileWithDeviceNo?userDeviceInfo={userDeviceInfo}")]
string LogInForMobileWithDeviceNo(clsUserDeviceInfo userDeviceInfo);

WCF REST POST of JSON: Parameter is empty

Using Fiddler I post a JSON message to my WCF service. The service uses System.ServiceModel.Activation.WebServiceHostFactory
[OperationContract]
[WebInvoke
(UriTemplate = "/authenticate",
Method = "POST",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.WrappedRequest
)]
String Authorise(String usernamePasswordJson);
When the POST is made, I am able to break into the code, but the parameter usernamePasswordJson is null. Why is this?
Note: Strangly when I set the BodyStyle to Bare, the post doesn't even get to the code for me to debug.
Here's the Fiddler Screen:
You declared your parameter as type String, so it is expecting a JSON string - and you're passing a JSON object to it.
To receive that request, you need to have a contract similar to the one below:
[ServiceContract]
public interface IMyInterface
{
[OperationContract]
[WebInvoke(UriTemplate = "/authenticate",
Method = "POST",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare)]
String Authorise(UserNamePassword usernamePassword);
}
[DataContract]
public class UserNamePassword
{
[DataMember]
public string UserName { get; set; }
[DataMember]
public string Password { get; set; }
}