I want to post json object to my WCF service
My only problem is his date property. I get the date from an jquery datepicker and i want to get it in my service as c# datetime.
My service:
namespace Employee
{
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebInvoke(Method = "POST",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped)]
bool UpdateEmployee(Employee Employee);
}
}
And this is Employee:
[DataContract]
public class Employee
{
[DataMember]
public string Name { get; set; }
[DataMember]
public string Department { get; set; }
[DataMember]
public int Salary { get; set; }
[DataMember]
public DateTime Hired { get; set; }
}
All the other properties work fine. I just need to convert my date string to json date.
The expected format for DateTime object is not the format returned by jQuery's date picker. WCF expects the date in the ASP.NET format (e.g., \/Date(1234567890)\/).
You can use other formats, though, but it's not simple (at least not until .NET 4.0; on 4.5 this got a lot better). Basically, you'd use a string property (which can be private, if your service is running under full trust) which would get the value from the wire, then hook it up to a DateTime property during the serialization episodes. There's more information about this trick at http://blogs.msdn.com/b/carlosfigueira/archive/2011/09/06/wcf-extensibility-serialization-callbacks.aspx, and you can see it on the code below.
namespace StackOverflow_11105856
{
[ServiceContract]
public interface IService1
{
[OperationContract]
[WebInvoke(Method = "POST",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped)]
string UpdateEmployee(Employee Employee);
}
public class Service : IService1
{
public string UpdateEmployee(Employee Employee)
{
return string.Format("Name={0},Hired={1}", Employee.Name, Employee.Hired.ToString("yyyy-MM-dd HH:mm:ss"));
}
}
[DataContract]
public class Employee
{
[DataMember]
public string Name { get; set; }
[DataMember]
public string Department { get; set; }
[DataMember]
public int Salary { get; set; }
public DateTime Hired { get; set; }
[DataMember(Name = "Hired")]
private string HiredForSerialization { get; set; }
[OnSerializing]
void OnSerializing(StreamingContext ctx)
{
this.HiredForSerialization = this.Hired.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
}
[OnDeserializing]
void OnDeserializing(StreamingContext ctx)
{
this.HiredForSerialization = "1900-01-01";
}
[OnDeserialized]
void OnDeserialized(StreamingContext ctx)
{
this.Hired = DateTime.ParseExact(this.HiredForSerialization, "MM/dd/yyyy", CultureInfo.InvariantCulture);
}
}
}
And the jQuery call:
function StackOverflow_11105856_Test() {
var url = "/StackOverflow_11105856.svc/UpdateEmployee";
var data = {
Name: "John Doe",
Department: "Accounting",
Salary: 50000,
Hired: $("#StackOverflow_11105856_datepicker").val()
};
$.ajax({
type: 'POST',
url: url,
contentType: "application/json",
data: JSON.stringify({ Employee: data }),
success: function (result) {
$("#result").text(result.UpdateEmployeeResult);
}
});
}
You should try changing the property BodyStyle = WebMessageBodyStyle.Wrapped to BodyStyle = WebMessageBodyStyle.Bare. This way the framework won't add any extra XML decorations.
Also, you should check the date format coming from the client.
Perhaps you should send it from the client in a pre-set format and then have a string property in your object, rather than a DateTime one.
You can add a read-only property which converts the date string to a DateTime, using the already known format.
Related
In Asp.Net core I have a razor page and I want to send a Ajax post to a Post method but always I get null model.here is my simplify question.
public class IndexModel : PageModel
{
public void OnPost([FromBody]A A)
{
if (ModelState.IsValid)
{
}
}
}
and this is my model:
[JsonObject(MemberSerialization.OptOut)]
public class A
{
[JsonProperty]
public string Id { get; set; }
[JsonProperty]
public string CityId { get; set; }
[JsonProperty]
public string Infected { get; set; }
[JsonProperty]
public string Susceptible { get; set; }
[JsonProperty]
public string Recovered { get; set; }
[JsonProperty]
public string CityName { get; set; }
}
This is my Ajax request:
function f(event) {
var token = $("input[name='__RequestVerificationToken']").val();
var c = {};
c["Id"] = "1";
c["CityId"] = "2";
c["Infected"] = "3";
c["Susceptible"] = "4";
c["Recovered"] = "5";
c["CityName"]=""
$.ajax({
url: "./DynamicEpidemic",
type: "post",
contentType: 'application/json; charset=utf-8',
headers:
{
"RequestVerificationToken": token
},
data: { A: JSON.stringify(c)},
success: function () {
alert("OK");
}
});
console.log(JSON.stringify(c));
}
and sent json object is like this:
{"Id":"1","CityId":"2","Infected":"3","Susceptible":"4","Recovered":"5","CityName":""}
but my model is always null.ModelState error is
Unexpected character encountered while parsing value: A. Path '', line 0, position 0.
Try changing to data: JSON.stringify(c).
how to post call SaveCorporateProfile function by passing json
[DataContract]
public class myclass
{
public string CompanyCode { get; set; }
public string Username { get; set; }
public string Password { get; set; }
}
[ServiceContract]
public interface ICustProfileService
{
[OperationContract]
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "/SaveCorporateProfile?dt={dt}")]
string SaveCorporateProfile(myclass dt);
}
public string SaveCorporateProfile(myclass dt)
{
return "success";
}
You can try this;
Firstly, you should edit your myclass like this;
[DataContract]
public class myclass
{
[DataMember]
public string CompanyCode { get; set; }
[DataMember]
public string Username { get; set; }
[DataMember]
public string Password { get; set; }
}
then your interface like this;
[ServiceContract]
public interface ICustProfileService
{
[OperationContract]
string SaveCorporateProfile(myclass dt);
}
And you implement your .svc file for using this interface
public class CustProfileService: ICustProfileService
{
[WebInvoke(Method = "POST",UriTemplate = "/SaveCorporateProfile?dt={dt}"
BodyStyle = WebMessageBodyStyle.Bare,
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)]
public string SaveCorporateProfile(myclass dt)
{
return "success";
}
}
I have to create a post request in Json in this format.
{
"request": {
"application": "APPLICATION_CODE",
"auth": "API_ACCESS_TOKEN",
"notifications": [{
"send_date": "now", // YYYY-MM-DD HH:mm OR 'now'
"ignore_user_timezone": true, // or false
"content": "Hello world!"
}]
}
}
This is my first time serializing Json String and I have no idea how to do this, I have tried a few different things but could never get the exact format.
Would really appreciate any kind of help.
Thanks!
First, you cannot put comment on a json file, but I guess it was just there for now.
Then you can paste your json in converters like this one http://json2csharp.com/
And you get the following:
public class Notification
{
public string send_date { get; set; }
public bool ignore_user_timezone { get; set; }
public string content { get; set; }
}
public class Request
{
public string application { get; set; }
public string auth { get; set; }
public List<Notification> notifications { get; set; }
}
public class RootObject
{
public Request request { get; set; }
}
Now you need to fix a few issues that are required for JsonUtility:
[Serializable]
public class Notification
{
public string send_date;
public bool ignore_user_timezone;
public string content;
}
[Serializable]
public class Request
{
public string application;
public string auth;
public List<Notification> notifications;
}
[Serializable]
public class RootObject
{
public Request request;
}
Finally:
RootObject root = JsonUtility.FromJson<RootObject>(jsonStringFile);
You can also use SimpleJSON like this ;
string GetRequest () {
JSONNode root = JSONNode.Parse("{}");
JSONNode request = root ["request"].AsObject;
request["application"] = "APPLICATION_CODE";
request["auth"] = "API_ACCESS_TOKEN";
JSONNode notification = request ["notifications"].AsArray;
notification[0]["send_date"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
notification[0]["ignore_user_timezone"] = "true";
notification[0]["content"] = "Hello world!";
return root.ToString ();
}
I am a newbie to web api,not able to find the error while passing json message to a web api controller. I am using fiddler client to post complex type(model object). My model is always null. It is not reading from the json post object. What am I doing wrong?
My model:
public class LocationModel
{
public int Customer {get; set;}
public string Name { get; set; }
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string Area { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Country { get; set; }
}
My controller:
public class LocationController : ApiController
{
[HttpPost]
public bool AddLocation([FromBody] LocationModel model)
{
MysqlRepository reps = new MysqlRepository();
if (reps.LocationInsert(model))
{
return true;
}
else
{
return false;
}
}
}
Json message(post using fiddler client):
var LocationModel = {
Customer:9,
Name: "test",
AddressLine1:"rrr",
AddressLine2:"rrr",
Area:"ddd",
City:"ddd",
State:"cooo",
Country:"kkk"
}
$.ajax({
url: 'api/Location',
type: 'POST',
data: JSON.stringify(LocationModel),
dataType: 'json',
contentType: "application/json",
success: function (data) {
}
});
Being new to fiddler tool i passed header info at body ...thats why input not passed from tool....
correct way is to pass in fiddler body as:
{
"Customer":9,
"Name": "test",
"AddressLine1":"rrr",
"AddressLine2":"rrr",
"Area":"ddd",
"City":"ddd",
"State":"cooo",
"Country":"kkk"
}
I have a working WCF service which used JSON as its RequestFormat and ResponseFormat.
[ServiceContract]
public interface IServiceJSON
{
[OperationContract]
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
MyClassA echo(MyClassA oMyObject);
}
[DataContract]
public class MyClassA
{
[DataMember]
public string message;
[DataMember]
public List<MyClassB> myList;
public MyClassA()
{
myList = new List<MyClassB>();
}
}
[DataContract]
public class MyClassB
{
[DataMember]
public int myInt;
[DataMember]
public double myDouble;
[DataMember]
public bool myBool;
[DataMember]
public DateTime myDateTime;
}
The myDateTime property of class MyClassB is of type DateTime. This is being serialized to the following format: "myDateTime":"/Date(1329919837509+0100)/"
The client I need to communicate with can not deal with this format. It requires it to be a more conventional format like for example: yyyy-MM-dd hh:mm:ss
Is it somehow possible to add this to the DataMember attribute? Like so:
[DataMember format = “yyyy-MM-dd hh:mm:ss”]
public DateTime myDateTime;
Thanks in advance!
Here's an example of the already checked answer...
[DataContract]
public class ProductExport
{
[DataMember]
public Guid ExportID { get; set; }
[DataMember( EmitDefaultValue = false, Name = "updateStartDate" )]
public string UpdateStartDateStr
{
get
{
if( this.UpdateStartDate.HasValue )
return this.UpdateStartDate.Value.ToUniversalTime().ToString( "s", CultureInfo.InvariantCulture );
else
return null;
}
set
{
// should implement this...
}
}
// this property is not transformed to JSon. Basically hidden
public DateTime? UpdateStartDate { get; set; }
[DataMember]
public ExportStatus Status { get; set; }
}
The class above defines two methods to handle the UpdateStartDate. One that contains the nullable DateTime property, and the other convert the DateTime? to a string for the JSon response from my service.
Why not just pass it as an already formatted string?
That is, don't pass the date in your DataContract as a date. Make that member a string instead, and format the string the way your client it wants it.