How to Convert Json Result to Object in c# mvc - c#

I am trying to convert this response to object so that i can use access them using object in c# mvc application.
Following is the code i did:
var response = await client.GetAsync("ApiTest?Amount=" + Amount.ToString() + "&WalletAddress=" + WalletAddress.ToString() + "&TokenCode=" + TokenType.ToString());
if (response.IsSuccessStatusCode)
{
result = response.Content.ReadAsStringAsync().Result;
var test1 = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(result);
(Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(result));
result = await response.Content.ReadAsStringAsync();
var obj =Newtonsoft.Json.JsonConvert.DeserializeObject(result);
return Json(new { Message = "Your Transaction Has Been Completed Successfully!" }, JsonRequestBehavior.AllowGet);
}
Following is the Json response but its in string format:
{"Error":"Transaction amount must be greater than
0","Result":null,"IsSuccess":false,"HttpResponse":{"Headers":[{"Key":"X-Frame-Options","Value":["sameorigin"]},{"Key":"Strict-Transport-Security","Value":["max-age=31536000"]},{"Key":"Pragma","Value":["no-cache"]},{"Key":"Access-Control-Allow-Origin","Value":["*"]},{"Key":"Keep-Alive","Value":["timeout=5, max=100"]},{"Key":"Connection","Value":["Keep-Alive"]},{"Key":"Cache-Control","Value":["no-store,
must-revalidate, no-cache, post-check=0,
pre-check=0"]},{"Key":"Date","Value":["Wed, 28 Feb 2018 09:43:57
GMT"]},{"Key":"Set-Cookie","Value":["PHPSESSID=3vbjmnpea9i9n871a8knc3s89q7lufpn;
path=/; secure;
HttpOnly","visid_incap_992349=On7CIEXMQBq9AtX5/PvHQtp5lloAAAAAQUIPAAAAAACXLL2Z399YXaT6IXztsol+;
expires=Wed, 27 Feb 2019 14:49:04 GMT; path=/;
Domain=.coinpayments.net","incap_ses_478_992349=pCsbJzCRvCFLbgPwODOiBtx5lloAAAAAR8gvl6uEmcAX0kCi3b/2Ig==;
path=/;
Domain=.coinpayments.net"]},{"Key":"Server","Value":["Apache"]},{"Key":"X-Iinfo","Value":["5-23697956-23698018
NNNN CT(1461 273 0) RT(1519811034346 506) q(0 0 17 1) r(18 19)
U6"]},{"Key":"X-CDN","Value":["Incapsula"]}],"ContentBody":"{\"error\":\"Transaction
amount must be greater than
0\",\"result\":[]}","StatusCode":200,"IsSuccessStatusCode":true,"RequestUri":"https://www.coinpayments.net/api.php","RequestBody":"cmd=create_transaction\u0026amount=0\u0026currency1=USD\u0026currency2=LTCT\u0026buyer_email=3Pt5ebwZsMWV2ij1bnFv1yJYk2155PGzGx\u0026version=1\u0026key=c84f65f198e77895f3edc08e7654379785f1057c7c0c6115bee69ed68371d558"}}
any help would be highly appreciated>
Thanks

You can utilize Visual Studio's Paste Special feature:
Copy JSON and Paste Special:
You will get following classes:
public class JsonResponse
{
public string Error { get; set; }
public object Result { get; set; }
public bool IsSuccess { get; set; }
public Httpresponse HttpResponse { get; set; }
}
public class Httpresponse
{
public Header[] Headers { get; set; }
public string ContentBody { get; set; }
public int StatusCode { get; set; }
public bool IsSuccessStatusCode { get; set; }
public string RequestUri { get; set; }
public string RequestBody { get; set; }
}
public class Header
{
public string Key { get; set; }
public string[] Value { get; set; }
}
Now simply utilize Newtonsoft to deserialize:
var items = JsonConvert.DeserializeObject<JsonResponse>(json);
Output:

Try this:
using Newtonsoft.Json.Linq;
...
var jso = JObject.Parse(content);
string value = jso["propertyname"].Value<string>();

Related

Deserialize object into own type in C#

I am new to c# and I am willing to convert a Object into a class representing a User. I am retrieving the object from a http request to an API. My code is:
private async void getUser()
{
var requestURI = new HttpRequestMessage();
string url = "https:...";
requestURI.RequestUri = new Uri(url);
requestURI.Method = HttpMethod.Get;
requestURI.Headers.Add("Accept", "application/json");
HttpResponseMessage responseURI = await client.SendAsync(requestURI);
if (responseURI.StatusCode == HttpStatusCode.OK)
{
Debug.WriteLine("Get User OK");
var UserString = await responseURI.Content.ReadAsStringAsync();
Debug.WriteLine("User: " + UserString);
var UsersJson = JsonConvert.DeserializeObject(UsersString);
Debug.WriteLine(UserJson);
}
else
{
Debug.WriteLine("User GET request failed");
}
}
The output is:
{
"Username": "Alice",
"IP": "192.13.2.2",
"Levels": "1,2"
}
How do I create a class or a type to later deserealize this object into it? When the type/class is created, how do I deserealize the object into it?
Thanks in advice
You can use this website - https://json2csharp.com/ - to generate the C# classes.
In this case, the class would be as follows:
public class User
{
public string Username { get; set; }
public string IP { get; set; }
public string Levels { get; set; }
}
For deserialization to this class, you can use as follows:
var user = JsonConvert.DeserializeObject<User>(UsersString);
public class User
{
public string Username { get; set; }
public string IP { get; set; }
public string Levels { get; set; }
}
The you Deserialize an Object like this: Please have a look at this https://www.newtonsoft.com/json/help/html/SerializingJSON.htm
var user = JsonConvert.DeserializeObject<User>(json);

My xamarin app freezes when i try JsonConvert.DeserializeObject <T>

When I get a json response from HttpClient () and try to deselize, my Xamarin application freezes (UI works, but the code after in class ExecuteGetRequest line 15 does not work). What can it be because of?
No errors.
I call the method of obtaining a list of anime user
ShikimoriMain shikimoriMain = new ShikimoriMain();
var UserInformation = await shikimoriMain.GetUserInformation(Convert.ToInt64(UserID));
var UserAnimeList = await shikimoriMain.GetUserAnimeList(Convert.ToInt64(UserID), 1, 5);
string animeName = UserAnimeList.Anime[0].Anime.Name;
ShikimoriMain.GetUserAnimeList
public async Task<ShikimoriUserAnimeList> GetUserAnimeList(long id, int page, int limit)
{
string[] args = new string[] { ShikimoriCategories.UserID + "/" + id + ShikimoriCategories.UserAnimeList + $"?limit={limit}&page={page}" };
return await ExecuteGetRequest<ShikimoriUserAnimeList>(args);
}
ExecuteGetRequest
public async Task<T> ExecuteGetRequest<T>(string[] args) where T : class
{
T returnedObject;
using (var client = new HttpClient())
{
// client.BaseAddress = new Uri($"{httpApiv1}/{args}");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, httpApiv1 + String.Join("/", args));
request.Headers.TryAddWithoutValidation("User-Agent", "Search Anime");
HttpResponseMessage responseMessage = await client.SendAsync(request);
string json = await responseMessage.Content.ReadAsStringAsync(); // successfully get json
returnedObject = JsonConvert.DeserializeObject<T>(json); // after that the code is not executed
return returnedObject;
}
}
ShikimoriUserAnimeList
public class ShikimoriUserAnimeList
{
[JsonProperty()]
public List<GetAnime> Anime { get; set; }
}
public class GetAnime
{
[JsonProperty("id")]
public int ID { get; set; }
[JsonProperty("status")]
public string Status { get; set; }
[JsonProperty("anime")]
public Anime Anime { get; set; }
}
public class Anime
{
[JsonProperty("id")]
public int ID { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("russian")]
public string NameRU { get; set; }
[JsonProperty("image")]
public AnimeImage AnimeImage { get; set; }
[JsonProperty("kind")]
public string King { get; set; }
[JsonProperty("score")]
public string Score { get; set; }
[JsonProperty("status")]
public string Status { get; set; }
[JsonProperty("episodes")]
public int Episodes { get; set; }
}
public class AnimeImage
{
[JsonProperty("original")]
public string Original { get; set; }
[JsonProperty("preview")]
public string Preview { get; set; }
[JsonProperty("x96")]
public string ImageX96 { get; set; }
[JsonProperty("x48")]
public string ImageX48 { get; set; }
}
For the sake of completion:
An error was being thrown but was not visible in the device log. Wrapping the JsonConvert.DeserializeObject<T>(json) in a try catch block helped finding the Exceptionbeing thrown.
try
{
returnedObject = JsonConvert.DeserializeObject<T>(json); // after that the code is not executed
return returnedObject;
}
catch (Exception ex)
{
... (debug and fix the error that occurred)
}
I had same problem, I've realized that using HttpClient async will cause deadlock in winforms or xamarin (however it works well with Asp) and I changed these lines
HttpResponseMessage responseMessage = await client.SendAsync(request);
string json = await responseMessage.Content.ReadAsStringAsync(); // successfully get json
Like these (Make them work synchronous):
HttpResponseMessage responseMessage = client.SendAsync(request).Result;
string json = responseMessage.Content.ReadAsStringAsync().Result; // successfully get json
And change your method as default synchronous
Take a look at Here

Connecting to REST Api and retrieving JSON

I am connecting to an API, but not having any luck retrieving the data in Json. I have different endpoints to use, but cant seem the any to work. I believe /products should give me the entire list but am having no luck.
class Program
{
static void Main(string[] args)
{
RunAsync().Wait();
}
static async Task RunAsync()
{
using (var client = new HttpClient())
{
//go get the data
string token = "auth token";
client.BaseAddress = new Uri("");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
Console.WriteLine("GET");
HttpResponseMessage response = await client.GetAsync("/products/6");
if (response.IsSuccessStatusCode)
{
Console.WriteLine("Connected");
RootObject product = await response.Content.ReadAsAsync<RootObject>();
Console.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}", product.data.id,product.data.name,product.data.sort,product.data.designation_id,product.data.designation_id);
}
else
{
Console.WriteLine("Failed");
Console.WriteLine(response.Headers);
}
}
}
}
The response I am getting in the console on this is:
0
1/1/0001 12:00:00 AM
1/1/0001 12:00:00 AM
Product class:
public class RootObject
{
public Product data { get; set; }
}
public class Product
{
public int id { get; set; }
public object designation_id { get; set; }
public string name { get; set; }
public object alternate_name { get; set; }
public object description { get; set; }
public int sort { get; set; }
public string created_at { get; set; }
public string updated_at { get; set; }
}
The response I get when testing connection with postman is as follows:
{
"data": {
"id": 6,
"designation_id": null,
"name": "Multirate Fork Springs Kit",
"alternate_name": null,
"description": null,
"sort": 0,
"created_at": "2016-06-17 20:47:51",
"updated_at": "2018-05-25 09:40:50"
}
}
nuget Newtonsoft.Json
and you can do something like this:
using Newtonsoft.Json;
in client, using response
Product product = JsonConvert.DeserializeObject<Product>(your response string);
this works really well, as long as your product class has all the right attributes you should be good to go!

ReadAsAsync deserializing HttpResponseMessage result

This queston may possible duplicated but I am calling a service as the following below :
HttpClient httpClinet = new HttpClient();
httpClinet.DefaultRequestHeaders.Accept.Clear();
httpClinet.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/xml"));
var str = "XrayService.asmx/GetOrdData?" + string.Format("ordId={0}&code={1}", range.ordId, range.code);
HttpResponseMessage response;
httpClinet.BaseAddress = new Uri("http://172.16.203.27:6043/");
response = httpClinet.GetAsync(str).Result;
if (response.IsSuccessStatusCode)
var caseInfos = response.Content.ReadAsAsync<IEnumerable<PI>>().Result;//Here is exception
everything is going fine, but when I want to run ReadAsAsync I got the exception as below:
Error:System.AggregateException: One or more errors occurred. ---> System.AggregateException: One or more errors occurred. ---> System.Runtime.Serialization.SerializationException: Error in line 1 position 5. Expecting element 'ArrayOfPI' from namespace 'http://schemas.datacontract.org/2004/07/SATA_DTOs'.. Encountered 'Element' with name 'PI', namespace ''.
at System.Runtime.Serialization.DataContractSerializer.InternalReadObject(XmlReaderDelegator xmlReader, Boolean verifyObjectName, DataContractResolver dataContractResolver)
at System.Runtime.Serialization.XmlObjectSerializer.ReadObjectHandleExceptions(XmlReaderDelegator reader, Boolean verifyObjectName, DataContractResolver dataContractResolver)
at System.Runtime.Serialization.DataContractSerializer.ReadObject(XmlReader reader)
at System.Net.Http.Formatting.XmlMediaTypeFormatter.ReadFromStream(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
at System.Net.Http.Formatting.XmlMediaTypeFormatter.ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
--- End of stack trace from previous location where exception was thrown ---
I am testing that service by Google Advanced Rest Client and see the result as :
Status : 200 OK
Response Header:
cache-control: private, max-age=0
content-length: 360
content-type: text/xml; charset=utf-8
server:Microsoft-IIS/8.5
x-aspnet-version:4.0.30319
x-powered-by: ASP.NET
date: Sun, 03 Dec 2017 08:37:21 GMT
and OutPut :
<?xml version="1.0" encoding="utf-8" ?>
<PI>
<ordId>950177248</ordId>
<fnm>بهسا</fnm>
<lnm>حسنی</lnm>
<fthNm>علی</fthNm>
<pId>p2535154</pId>
<sex>F</sex>
<brthD>2003-02-05</brthD>
<addrs />
<nId>0025351540</nId>
<srvNm>|دندان بصورت پانورک</srvNm>
<rfrPhy>مهرزاد اميري-41853</rfrPhy>
</PI>
I also decorated DTO like :
namespace SATA_DTOs
{
[DataContract(Name = "PI")]
public class PI
{
[DataMember] public string ordId { get; set; }
[DataMember] public string fnm { get; set; }
[DataMember] public string lnm { get; set; }
[DataMember] public string fthNm { get; set; }
[DataMember] public string pId { get; set; }
[DataMember] public string sex { get; set; }
[DataMember] public string brthD { get; set; }
[DataMember] public string addrs { get; set; }
[DataMember] public string nId { get; set; }
[DataMember] public string srvNm { get; set; }
[DataMember] public string rfrPhy { get; set; }
}
}
UPDATE:
Just as another try I want to get the result here either JSON or XML but this is also does not make difference:
List<PI> model = null;
var client = new HttpClient();
var task = client.GetAsync(httpClinet.BaseAddress.ToString() + str)
.ContinueWith((taskwithresponse) =>
{
var response1 = taskwithresponse.Result;
var jsonString = response1.Content.ReadAsStringAsync();
m_Logging.Log(SharedLib.LoggingMode.Prompt, "JSON string created {0}...", jsonString);
jsonString.Wait();
model = Newtonsoft.Json.JsonConvert.DeserializeObject<List<PI>>(jsonString.Result);
});
task.Wait();
After many copy pasting patch on server and improving the log I finally resolve the problem,
As the last try which #NKosi suggested with little changes:
var response1 = httpClinet.GetAsync(str).Result;
IEnumerable<PI> caseInfos1 = Enumerable.Empty<PI>();
try
{
caseInfos1 = response1.Content.ReadAsAsync<IEnumerable<PI>>().Result;
}
catch (Exception ex)
{
try
{
m_Logging.Log(SharedLib.LoggingMode.Error, "IEnumerable failed, EXP:{0}", ex);
var singleObject = response1.Content.ReadAsAsync<PI>().Result;
if (singleObject != null)
{
m_Logging.Log(SharedLib.LoggingMode.Error, "singleObject succeeded...");
caseInfos1 = new[] { singleObject };
}
}
catch (Exception exp)
{
m_Logging.Log(SharedLib.LoggingMode.Error, "singleObject failed, EXP:{0}", exp);
}
}
I crossed with the below exception also:
System.Runtime.Serialization.SerializationException: Error in line 1 position 5. Expecting element 'ArrayOfPI' from namespace 'http://schemas.datacontract.org/2004/07/SATA_DTOs'.. Encountered 'Element' with name 'PI', namespace ''....
.....
as the exception mentioned it can't be able to deserialize the result I guessed the out put type may is text/html not text/xml although Rest Client Tester specified it as text/xml,
for this reason I came to this conclusion to use ReadAsStringAsync and deserialize it to PI, so by the below snipped code I finally get the result:
PI caseInfos = null;
try
{
string strasd = response.Content.ReadAsStringAsync().Result;
m_Logging.Log(SharedLib.LoggingMode.Prompt, "ReadAsStringAsync() result:{0}", strasd);
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(PI));
using (TextReader reader = new StringReader(strasd))
caseInfos = (PI)serializer.Deserialize(reader);
m_Logging.Log(SharedLib.LoggingMode.Prompt, "Deserializing caseInfos model succeeded...");
}
catch (Exception ex)
{
m_Logging.Log(SharedLib.LoggingMode.Error, "creating model failed, EXP:{0}", ex);
}
I appreciate all crossed this question especially those who shared his/her knowledge in this discussion!!!
This is can be quite confusing. This might seem obvious the eye but still, not understandable to some.
Look at this line:
var caseInfos = response.Content.ReadAsAsync<IEnumerable<PI>>().Result
You are rendering the result as PI, which results in <pi> tag.
Thus, you get the following error:
System.Runtime.Serialization.SerializationException: Error in line 1
position 5. Expecting element 'ArrayOfPI' from namespace
'http://schemas.datacontract.org/2004/07/SATA_DTOs'.. Encountered
'Element' with name 'PI', namespace ''
The solution is this,
change your data contract and your class name:
namespace SATA_DTOs
{
[DataContract(Name = "ArrayOfPI")]
public class ArrayOfPI
{
[DataMember] public string ordId { get; set; }
[DataMember] public string fnm { get; set; }
[DataMember] public string lnm { get; set; }
[DataMember] public string fthNm { get; set; }
[DataMember] public string pId { get; set; }
[DataMember] public string sex { get; set; }
[DataMember] public string brthD { get; set; }
[DataMember] public string addrs { get; set; }
[DataMember] public string nId { get; set; }
[DataMember] public string srvNm { get; set; }
[DataMember] public string rfrPhy { get; set; }
}
}
Then assign it like this:
var caseInfos = response.Content.ReadAsAsync<IEnumerable<ArrayOfPI>>().Result
Thus, you will receive this:
<?xml version="1.0" encoding="utf-8" ?>
<ArrayOfPI>
<ordId>950177248</ordId>
<fnm>بهسا</fnm>
<lnm>حسنی</lnm>
<fthNm>علی</fthNm>
<pId>p2535154</pId>
<sex>F</sex>
<brthD>2003-02-05</brthD>
<addrs />
<nId>0025351540</nId>
<srvNm>|دندان بصورت پانورک</srvNm>
<rfrPhy>مهرزاد اميري-41853</rfrPhy>
</ArrayOfPI>
Which is what the serialization looks for and expects to find.
When using ReadAsAsync the framework tries to interpret the desired type for deserialization using the provided media type formatter.
You have IEnumerable<PI> so it assumes that the content being read is a collection ArrayOfPI based on standards.
In your example a single object is being returned while you tell it to expect a collection so it fails.
I suggest checking for collection and if that fails then check for single object given the dynamic nature of the responses that can be returned.
Simplified example
public async Task<IEnumerable<PI>> GetDataAsync() {
var httpClinet = buildClient();
var str = buildRequestUrl();
var response = await httpClinet.GetAsync(str);
IEnumerable<PI> caseInfos = Enumerable.Empty<PI>();
if (response.IsSuccessStatusCode) {
try {
caseInfos = await response.Content.ReadAsAsync<IEnumerable<PI>>();
} catch {
//Log?
}
if (caseInfos == null) {
try {
var singleObject = await response.Content.ReadAsAsync<PI>();
if (singleObject != null) {
caseInfos = new[] { singleObject };
}
} catch {
//Log?
}
}
}
return caseInfos;
}

StatusCode: 401, ReasonPhrase: 'Unauthorized' gets displayed when calling a Post Method through HTTPClient using C#

I am trying to access an API's Post method through HTTP Client and passing the AuthToken. When I tried to access in post man I am able to get the response, but when I ran in C#, I got StatusCode: 401, ReasonPhrase: 'Unauthorized' error. I am sharing the request and Response screens of Postman along with my code. can anyone let me know the mistake which i did in the code and how to solve the issue.
Postman Request Header and Response Body
Postman Request Body
below is my C# code.
public class PostEmpData
{
public string cExternalGUID = "10134",
cEmployeeID = "10134", cLastName = "Anderson", cFirstName = "Derek", cAccessGroup = "", cActive = "A";
public int nCardNumber = 10134, nPayMethod = 2;
public string[] cGroupsList = new string[0] { };
public DateTime dHireDate = DateTime.Parse("1999 / 11 / 03"), dTermDate = DateTime.Parse("01 / 01 / 0001"), dRateEffectiveDate = DateTime.Parse("2017 - 07 - 15");
public decimal nPayRate = 1500;
}
public class PostEmployeeClass
{
public int _interfaceID { get; set; }
public int _errorCode { get; set; }
public string _errorDescription { get; set; }
public List<EmpPostResponse> respList;
}
public class EmpPostResponse
{
public string RetKey { get; set; }
public int ErrorCode { get; set; }
public string Description { get; set; }
public string Success { get; set; }
public string SecondaryList { get; set; }
}
static async Task<List<EmpPostResponse>> CallPostEmployeeAsync(object postdata)
{
Console.WriteLine("Post Employee Process Started");
PostEmployeeClass authclass = null;
List<EmpPostResponse> data = null;
HttpResponseMessage response = await client.PostAsJsonAsync("xxxxxxV2/api/ED907F98-9132-4C7D-B4D4-7648A2577F6D/Integration/employees", postdata);
response.EnsureSuccessStatusCode();
if (response.IsSuccessStatusCode)
{
Console.WriteLine("success");
authclass = await response.Content.ReadAsAsync<PostEmployeeClass>();
data = authclass.respList;
}
else
Console.WriteLine("fail:" + response.StatusCode.ToString());
return data;
}
static void Main(string[] args)
{
Console.WriteLine("Starting the Process");
RunAsync().Wait();
}
static async Task RunAsync()
{
PostEmpData objPost = new PostEmpData();
client.BaseAddress = new Uri("https://xxxx.xxxxx.com/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
try
{
string AuthToken="XXXXXXXXXXXXX";
client.DefaultRequestHeaders.Add("AuthToken", AuthToken);
Console.WriteLine(AuthToken);
var postdata = CallPostEmployeeAsync(objPost);
}catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}
I've reviewed your code and there are a few things that I noticed.
One thing that is not going to work: PostEmpData will serialize into an empty object as it contains no properties. So the body will be something like: {}. You will need to add properties to the class:
public class PostEmpData
{
public string cExternalGUID { get; set; } = "10134";
public string cEmployeeID { get; set; } = "10134";
public string cLastName { get; set; } = "Anderson";
public string cFirstName { get; set; } = "Derek";
public string cAccessGroup { get; set; } = "";
public string cActive { get; set; } = "A";
public int nCardNumber { get; set; } = 10134;
public int nPayMethod { get; set; } = 2;
public string[] cGroupsList { get; set; }= new string[0] { };
public DateTime dHireDate { get; set; }= DateTime.Parse("1999 / 11 / 03");
public DateTime dTermDate { get; set; }= DateTime.Parse("01 / 01 / 0001");
public DateTime dRateEffectiveDate { get; set; }= DateTime.Parse("2017 - 07 - 15");
public decimal nPayRate { get; set; }= 1500;
}
There is a good chance that this causes the unauthorized response. And that it may have nothing to do with the token.
And there is also another difference compared to the Postman request. With Postman you send an array of object [{}], but with code you send one object. So you may have to post a list of PostEmpData.

Categories

Resources