Click here to Skip to main content
15,911,762 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi,
I need to implement syncing accounting items to cloud,so I have already WCF methods to sync but I want web API to post json data and then it store in web DB.

like earlier we made a get method for android application and return data in json format.

[AcceptVerbs("Get")]
        public DataTable Inflow(long TenantId, long SalesPersonId)
        {
            DataTable dtReceivable = new DataTable();
return dtReceivable 
}


for this android developer was calling this url like

MyURL/api/MobileAPI/Inflow?TenantId=1234&SalesPersonId=22
and then getting data in json format

Now I want to create a Post Method for syncing with web DB.
string JsonString = Inventory();


I need to pass this json string with TenantId.
I want to post this via my URL like
using (HttpClient httpclient = new HttpClient())
                        {
string url = "http://localhost:51411/api/MobileAPI/Inventory?TenantId=" + CommonClass.tenantId + "";
                            String uriToCall = String.Format(url);
                            var content = new FormUrlEncodedContent(new[]
                            {
                            new KeyValuePair<string, string>("", str)
                            });
}

I am not getting how to start so please can anyone can help me.

What I have tried:

I tried this by reading some google articles but still its not fine....
string str = Inventory();
    //HttpClient http = new HttpClient();
    using (HttpClient httpclient = new HttpClient())
    {


        var http = (HttpWebRequest)WebRequest.Create(new Uri("http://localhost:51411/api/MobileAPI/Inventory?TenantId='" + CommonClass.tenantId + "'&JsonInventory='" + str));
        http.Accept = "application/json";
        http.ContentType = "application/json";
        http.Method = "POST";
    }


and my web API code is
[HttpPost]
       [AcceptVerbs("POST")]
       public HttpResponseMessage Inventory(long TanantId, [FromBody]string JsonInventory)
       {
           try
           {
               List<Inventory> lstInventory = JsonConvert.DeserializeObject<List<Inventory>>(JsonInventory);
               foreach (var item in lstInventory)
               {

               }
               return new HttpResponseMessage(HttpStatusCode.OK);
           }
           catch (Exception ex)
           {
               throw ex;
           }
       }


My Inventory Model is this

public class Inventory
    {
        public string ItemId { get; set; }
        public string Category { get; set; }
        public decimal Price1 { get; set; }
        public string Description { get; set; }
        public int QuantityAvailable { get; set; }
        public int QuantityOnHand { get; set; }
        public string Method { get; set; }
    }


i am troubling to call this url from window application even my web application is also on running mode.
Posted
Updated 9-Jun-17 18:17pm
v3

You're close! :)
HttpClient http = new HttpClient();
string url = "http://localhost:51411/api/MobileAPI/Inventory?TenantId=" + CommonClass.tenantId;
StringContent content = new StringContent(JsonString, null, "application/json");
HttpResponseMessage response = await http.PostAsync(url, content);
response.EnsureSuccessStatusCode();

NB: The HttpClient class should not be wrapped in a using block:
You're using HttpClient wrong and it is destabilizing your software | ASP.NET Monsters[^]


catch (Exception ex)
{
    throw ex;
}

Don't do that! You've just destroyed the stack trace, which will make it impossible to track down the source of the error.

If you really must re-throw an exception, without wrapping it in a new exception, just use throw; without the ex:
C#
catch (Exception ex)
{
    // Do something with the exception here...
    throw;
}

But in this case, since you're not doing anything with the exception, just remove the try..catch block.
 
Share this answer
 
There are couple of ways that you can use inside the client code:

1. Use out-of the box nuget package, e.g. RestSharp. This allows you to invoke any HTTP request with the verbs supported as per HTTP 1.1 specifications. The library has RestClient and RestRequest classes. Please refer to the documentation at RestSharp - Simple REST and HTTP Client for .NET[^].

2. Use the built-in .NET framework types, like WebClient, or HttpWebRequest. The solution suggested by Richard here is exactly the one using WebClient.

Further, I noted that in the Web API (server) code, you are using serialized string as parameter from body - JsonInventory. However, you can use the Inventory type directly here, and no need to explicitly deserialize using Newtonsoft.Json library. In fact, the ASP.NET Web API takes care of it.
 
Share this answer
 
Thanks for your solution but I have solved it....my code is

string str = Inventory();
                        using (WebClient httpclient = new WebClient())
                        {
                            //string str = "abc";
                            string url = "http://localhost:51411/api/MobileAPI/Inventory?TenantId=" + CommonClass.tenantId;

                            ASCIIEncoding encoding = new ASCIIEncoding();
                            byte[] data = encoding.GetBytes(str);

                            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                            request.Method = "Post";
                            request.ContentLength = data.Length;
                            request.ContentType = "application/json";

                            using (Stream stream = request.GetRequestStream())
                            {
                                stream.Write(data, 0, data.Length);
                            }

                            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                        }


and my web API code like this

[HttpPost]
       [AcceptVerbs("POST")]
       async public Task Inventory(long TenantId)
       {
           try
           {
               byte[] data = await Request.Content.ReadAsByteArrayAsync();
               string JsonInventory = System.Text.Encoding.Default.GetString(data);
               List<Inventory> lstInventory = JsonConvert.DeserializeObject<List<Inventory>>(JsonInventory);
               foreach (var item in lstInventory)
               {

               }

           }
           catch (Exception ex)
           {
               throw ex;
           }
       }


public class Inventory
   {
       public string ItemId { get; set; }
       public string Category { get; set; }
       public decimal Price1 { get; set; }
       public string Description { get; set; }
       public int QuantityAvailable { get; set; }
       public int QuantityOnHand { get; set; }
       public string Method { get; set; }
   }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900