Get the object is null using JSON in WCF Service
I have made a demo, wish it is useful to you.
Server-side.
class Program
{
static void Main(string[] args)
{
Uri uri = new Uri("http://localhost:2000");
WebHttpBinding binding = new WebHttpBinding();
using (ServiceHost sh=new ServiceHost(typeof(MyService),uri))
{
ServiceEndpoint se = sh.AddServiceEndpoint(typeof(IService), binding, "");
se.EndpointBehaviors.Add(new WebHttpBehavior());
Console.WriteLine("service is ready....");
sh.Open();
Console.ReadLine();
sh.Close();
}
}
}
[ServiceContract(ConfigurationName ="isv")]
public interface IService
{
[OperationContract]
[WebInvoke(Method = "POST",
ResponseFormat = WebMessageFormat.Xml,
RequestFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.WrappedRequest,
UriTemplate ="BookInfo/")]
BookingResult Booking(BookInfo bookInfo);
}
[ServiceBehavior(ConfigurationName = "sv")]
public class MyService : IService
{
public BookingResult Booking(BookInfo bookInfo)
{
BookingResult result = new BookingResult();
if (bookInfo==null)
{
result.isSucceed = false;
}
else
{
result.isSucceed = true;
}
return result;
}
}
[DataContract]
public class BookInfo
{
[DataMember]
public string Name { get; set; }
}
[DataContract]
public class BookingResult
{
[DataMember]
public bool isSucceed { get; set; }
}
Client-side.
class Program
{
static void Main(string[] args)
{
string uri = "http://localhost:2000/BookInfo";
WebClient client = new WebClient();
client.Headers["Content-type"] = "application/json";
client.Encoding = Encoding.UTF8;
BookInfo input = new BookInfo()
{
Name = "Apple"
};
string str2 = "{\"bookInfo\":" + JsonConvert.SerializeObject(input) + "}";
string result = client.UploadString(uri, "POST", str2);
Console.WriteLine(result);
}
}
[DataContract]
public class BookInfo
{
[DataMember]
public string Name { get; set; }
}
Result.
If I call it in Postman.
Depending on the combination of BodyStyle, ResquestFormat and ResponseFormat. We will have the different formats.
1:
ResponseFormat = WebMessageFormat.Json,RequestFormat =
WebMessageFormat.Json, BodyStyle =
WebMessageBodyStyle.WrappedRequest,
Request:
{“bookInfo”:{“name”:”value”}}
Response:
{“BookingResult”:{“isSucceed”:value}}
2:
ResponseFormat = WebMessageFormat.Json,RequestFormat =
WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare,
Request:
{“name”:”value”}
Response:
{“isSucceed”:value}
3:
ResponseFormat = WebMessageFormat.Xml,RequestFormat = WebMessageFormat.Xml,BodyStyle = WebMessageBodyStyle.Bare,
Request:
<BookInfo xmlns="http://schemas.datacontract.org/2004/07/Server6" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<Name>true</Name>
</BookInfo>
Response.
<BookingResult xmlns="http://schemas.datacontract.org/2004/07/Server6" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<isSucceed>true</isSucceed>
</BookingResult>
4:
ResponseFormat = WebMessageFormat.Xml,RequestFormat WebMessageFormat.Xml,BodyStyle= WebMessageBodyStyle.Wrapped
Request:
<Booking xmlns="http://tempuri.org/">
<bookInfo>
<Name>abcd</Name>
</bookInfo>
</Booking>
Response:
<BookingResponse xmlns="http://tempuri.org/">
<BookingResult xmlns:a="http://schemas.datacontract.org/2004/07/Server6" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<a:isSucceed>true</a:isSucceed>
</BookingResult>
We could also use the MessageParameter attribute to assign the parameter’s name manually.
[return: MessageParameter(Name ="result")]
BookingResult Booking([MessageParameter(Name ="book")] BookInfo bookInfo);
Request:
{“book”:{“Name”:”value”}}
Response:
{“result”:{“isSucceed”:value}}
Feel free to contact me If you have any questions.
Sending JSON to WCF Rest Service - object is always null
If Wrapped is what you want to do, then you need to wrap the request in the operation parameter name:
var input = { "ContactCompanyObject" : newCustomer };
$.ajax({
data: input
...
});
Or for the second example, if you change the ajax call to the one shown below, you should get the expected result:
var input = { NullTestTypeObject: { NullTestString: "Hello", NullTestInt: 123} };
alert("Input: " + JSON.stringify(input));
$.ajax({
type: "POST",
url: "./Service1.svc/nulltestaddress/NullTestPost",
contentType: "application/json",
data: JSON.stringify(input),
success: function (result) {
alert("POST result: " + JSON.stringify(result));
}
});
JSON object posted null in wcf rest
The problem was the way of making JSON Object in my project I used JSONStringer and it worked fine.
Postman POST to WCF object is null
You should add DataMember
attibute to labellist
:
[DataContract]
public class Labels
{
private List<string> label;
[DataMember]
public List<string> labellist
{
get
{
return label;
}
set
{
label = value;
}
}
}
EDIT:
Also you need to send request as:
{"docs":{"labellist":["5015058942/0001/0000","5015298272/0001/0000"]}}
WCF REST POST of JSON: Parameter is empty
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; }
}
Related Topics
Read Big Txt File, Out of Memory Exception
How to Programmatically Limit My Program's CPU Usage to Below 70%
Wpf/C#: Where Should I Be Saving User Preferences Files
Finding Property Differences Between Two C# Objects
Project a Can't Reference a Class in Project B
Total Number of Items Defined in an Enum
How to Copy File - Access to the Path Is Denied
How to Connect and Use a SQLite Database from C#
Ensure That Httpconfiguration.Ensureinitialized()
Invalid Cast from 'System.Int32' to 'System.Nullable'1[[System.Int32, Mscorlib]]
What Is the Meaning of "This" in C#
Where Is My System.Numerics Namespace
Using Ssl and Sslstream for Peer to Peer Authentication
How to Implement Batch Fetching with Fluent Nhibernate When Working with Oracle
Best Practices: Throwing Exceptions from Properties
How to Maximize the Browser Window in Selenium Webdriver (Selenium 2) Using C#
How to Write a Unit Test to Determine Whether an Object Can Be Garbage Collected