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";
}
}
Related
I have a ViewModel which is initialized dto. I want to send json object from postman with their values but c# object can not take values and is set null. How can i do that ?
public class RegisterUserVm
{
public UserDto User { get; set; }
public RegisterUserVm()
{
User = new UserDto();
}
}
public class UserDto
{
public int Id { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
public string Email { get; set; }
public string Telephone { get; set; }
public string Password { get; set; }
}
[HttpPost]
[Route("RegisterUser")]
public async Task<ActionResult<UserDto>> RegisterUser([FromBody] RegisterUserVm vm)
{
var registeredUser = await userBusiness.RegisterUser(new RegisterUserCommand
{
User = vm.User
});
return registeredUser.Result;
}
[HttpPost]
[Route("RegisterUser")]
public async Task<IActionResult> RegisterUser([FromBody] RegisterUserVm vm)
{
var registeredUser = await userBusiness.RegisterUser(new RegisterUserCommand
{
User = vm.User
});
var resultModel = registeredUser.Result.ToResultModel();
return Ok(resultModel);
}
I created a WCF Rest Service. I try to Post method usage. I send request from client, request getting from service method. But request object (CompanyDTO) fields values are null. Where is problem? I could' nt find.
Service post method
public void SaveCompany(CompanyDTO NewCompany)
{
try
{
CompanyManager manager = new CompanyManager();
manager.Save(NewCompany);
WebOperationContext ctx = WebOperationContext.Current;
ctx.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.OK;
}
catch (Exception ex)
{
throw new FaultException(new FaultReason(ex.Message));
}
}
Contract service interface
[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = "SaveCompany")]
void SaveCompany(CompanyDTO NewCompany);
CompantDTO class
public class CompanyDTO
{
public string IDENTIFIER { get; set; }
public string TYPE { get; set; }
public string USER_TYPE { get; set; }
public string FIRST_NAME { get; set; }
public string MIDDLE_NAME { get; set; }
public string FAMILY_NAME { get; set; }
public string COMPANY_NAME { get; set; }
public Nullable<int> COMPANY_NO { get; set; }
public string LEGAL_OFFICE { get; set; }
public Nullable<System.DateTime> FOUNDATION_DATE { get; set; }
public string BOARDOFTRADE_NAME { get; set; }
public string BOARDOFTRADE_ID { get; set; }
public string MERSIS_NO { get; set; }
public string TAPDK_NO { get; set; }
public string TRADE_REGISTRATION_NO { get; set; }
public string TRADE_REGISTRATION_OFFICE { get; set; }
public string TAX_IDENTIFICATION_NO { get; set; }
public Nullable<System.DateTime> DIGITAL_SIGN_VALIDITY_DATE { get; set; }
public string TAX_OFFICE { get; set; }
public string TAX_OFFICE_CODE { get; set; }
public Nullable<short> STATUS { get; set; }
public Nullable<int> SYS_VERSION { get; set; }
public Nullable<System.DateTime> SYS_LAST_UPDATE { get; set; }
}
Client request body
{
"CompanyDTO":
{
"IDENTIFIER":"34501599398",
"TYPE":"1",
"USER_TYPE":"1",
"FIRST_NAME":"Ebru",
"MIDDLE_NAME":"sws",
"FAMILY_NAME":"sd",
"COMPANY_NAME":"NULL",
"COMPANY_NO": "123",
"LEGAL_OFFICE": "DSF",
"FOUNDATION_DATE":"2015-03-02",
"BOARDOFTRADE_NAME":"SAD",
"BOARDOFTRADE_ID":"ASD",
"MERSIS_NO":"DASD",
"TAPDK_NO":"NULASDASDL",
"TRADE_REGISTRATION_NO":"NULL",
"TRADE_REGISTRATION_OFFICE":"ADS",
"TAX_IDENTIFICATION_NO":"NUASDSALL",
"DIGITAL_SIGN_VALIDITY_DATE": "2015-03-02",
"TAX_OFFICE":"ASDAD",
"TAX_OFFICE_CODE":"ASDA",
"STATUS": "1",
"SYS_VERSION" : "1",
"SYS_LAST_UPDATE": "2015-03-02"
}
}
It seems you need to get rid of "CompanyDTO" in your json, so it looks likes this:
{
"IDENTIFIER":"34501599398",
"TYPE":"1",
"USER_TYPE":"1",
"FIRST_NAME":"Ebru",
"MIDDLE_NAME":"sws",
"FAMILY_NAME":"sd",
"COMPANY_NAME":"NULL",
"COMPANY_NO": "123",
"LEGAL_OFFICE": "DSF",
"FOUNDATION_DATE":"2015-03-02",
"BOARDOFTRADE_NAME":"SAD",
"BOARDOFTRADE_ID":"ASD",
"MERSIS_NO":"DASD",
"TAPDK_NO":"NULASDASDL",
"TRADE_REGISTRATION_NO":"NULL",
"TRADE_REGISTRATION_OFFICE":"ADS",
"TAX_IDENTIFICATION_NO":"NUASDSALL",
"DIGITAL_SIGN_VALIDITY_DATE": "2015-03-02",
"TAX_OFFICE":"ASDAD",
"TAX_OFFICE_CODE":"ASDA",
"STATUS": "1",
"SYS_VERSION" : "1",
"SYS_LAST_UPDATE": "2015-03-02"
}
I want to create a service which receives json object of one type and sends back different object. When im using same object type for request and response, everything is working. But when I change the object that im sending back I get bad request 400 can some one help?
public interface IOrderService
{
[OperationContract]
[WebInvoke(UriTemplate = "/GetTablesDataResponse",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json, Method = "POST")]
MetaDataResponseContract GetTablesDataResponse(TablesMetaDataContract TablesRequest);
}
}
TablesMetaDataContract
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
namespace GetMetaDataWcfSvc
{
[DataContract]
public class TablesMetaDataContract
{
[DataMember]
public Header Header { get; set; }
[DataMember]
public Body Body { get; set; }
}
[DataContract]
public class Header
{}
[DataContract]
public class Body
{
[DataMember]
public get_MetaData_request get_MetaData_request { get; set; }
}
[DataContract]
public class get_MetaData_request
{
[DataMember]
public service_control service_control { get; set; }
[DataMember]
public service_data service_data { get; set; }
}
[DataContract]
public class service_control
{
[DataMember]
public string application_src { get; set; }
[DataMember]
public string transaction_id { get; set; }
[DataMember]
public string process_name { get; set; }
[DataMember]
public string request_datetime { get; set; }
}
[DataContract]
public class service_data
{
[DataMember]
public tables_name tables_name { get; set; }
}
[DataContract]
public class tables_name
{
[DataMember]
public List<string> table_name { get; set; }
}
}
MetaDataResponseContract
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Runtime.Serialization;
using System.Web;
namespace GetMetaDataWcfSvc
{
[DataContract]
public class MetaDataResponseContract
{
[DataMember]
public service_status service_status { get; set;}
[DataMember]
public OutputParameters OutputParameters {get; set; }
}
[DataContract]
public class service_status
{
[DataMember]
public string return_code { get; set; }
[DataMember]
public string return_desc { get; set; }
}
[DataContract]
public class Column
{
[DataMember]
public string name { get; set; }
[DataMember]
public string sqltype { get; set; }
[DataMember]
public string text { get; set; }
}
[DataContract]
public class Row
{
[DataMember]
public List<Column> Column { get; set; }
}
[DataContract]
public class Table
{
[DataMember]
public string name { get; set; }
[DataMember]
public List<Row> Row { get; set; }
}
[DataContract]
public class OutputParameters
{
[DataMember]
public Table Table { get; set; }
}
}
Service function
public MetaDataResponseContract GetTablesDataResponse(TablesMetaDataContract TablesRequest)
{
TablesRequest.Body.get_MetaData_request.service_control.process_name = "server";
string ProcessName = TablesRequest.Body.get_MetaData_request.service_control.process_name;
string RequestDateTime = TablesRequest.Body.get_MetaData_request.service_control.request_datetime;
List<string> TablesList = new List<string> { };
GetDataTable(ProcessName);
MetaDataResponseContract TablesListResponse = new MetaDataResponseContract();
TablesListResponse.service_status.return_desc = "susccess";
//if i return TablesRequest and change return type in function it is working
return TablesListResponse;
}
client
DataContractJsonSerializer ser =
new DataContractJsonSerializer(typeof(TablesMetaDataContract));
MemoryStream mem = new MemoryStream();
ser.WriteObject(mem, TablesRequest);
string data =
Encoding.UTF8.GetString(mem.ToArray(), 0, (int)mem.Length);
WebClient webClient = new WebClient();
webClient.Headers["Content-type"] = "application/json";
webClient.Encoding = Encoding.UTF8;
try
{
string t = webClient.UploadString("http://localhost:63702/OrderService.svc/GetTablesDataResponse", "POST", data);
}
catch (Exception ex)
{
string x = ex.ToString();
}
I am developing an wcf-webservice. The consumer is able to choose between an atom-response and a json-response.
My OperationContract looks like this:
[OperationContract]
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate = "json/json")]
Result GetData();
The Result-Type contains some strings and an array of entries.
[DataContract]
public class Result
{
[DataMember]
public string baseUrl;
[DataMember]
public string url;
[DataMember]
public string title;
[DataMember]
public int totalResults;
[DataMember]
public JsonEntries[] resources;
}
I marked the JsonEntries also as DataContract:
[DataContract]
public class JsonEntries
{
[DataMember]
public string updated;
[DataMember]
public string key;
[DataMember]
public string title;
[DataMember]
public Salary salarie;
}
However, when i am trying to run this i get the error, that the metadata could not be called. When I am deleting the [DataMember] in front of the array, i get no error, but my response doesnt contain the array.
I've seen it work like this on various exmaples. So what am i doing wrong?
thanks in advance.
robidd
Should work, here is my code sample
DataContracts
[DataContract]
public class Result
{
[DataMember]
public int totalResults;
[DataMember]
public JsonEntries[] resources;
}
[DataContract]
public class JsonEntries
{
[DataMember]
public string title;
}
OperationContract
[OperationContract]
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate = "getdata")]
Result GetData();
public Result GetData()
{
var jsonEntries = new List<JsonEntries>
{
new JsonEntries {title = "1"},
new JsonEntries {title = "2"},
new JsonEntries {title = "3"}
}.ToArray();
return new Result
{
resources = jsonEntries,
totalResults = 1
};
}
my get call
private Bag<T> GetData<T>(string uri)
{
try
{
var request = (HttpWebRequest) WebRequest.Create(uri);
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
request.Headers[HttpRequestHeader.Authorization] = _authorizationData;
var response = (HttpWebResponse) request.GetResponse();
Stream stream = response.GetResponseStream();
var localStream = new MemoryStream();
CopyStream(stream, localStream);
stream.Close();
var result = JsonContractExtensions.Create<T>(localStream);
return new Bag<T>(result);
}
catch (WebException ex)
{
_log.Debug(ex);
return Bag<T>.Empty;
}
catch (Exception ex)
{
_log.Debug(ex);
return Bag<T>.Empty;
}
}
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.