如何制作post方法并从我的桌面应用程序中调用它 [英] How to make a post method and call it from my desktop application

查看:71
本文介绍了如何制作post方法并从我的桌面应用程序中调用它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我需要将同步会计项目实施到云端,所以我已经有WCF方法进行同步,但我希望Web API发布json数据,然后将其存储在Web数据库中。 />


就像之前我们为Android应用程序制作一个get方法并以json格式返回数据。



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




这个Android开发人员的
称这个网址为



MyURL / api / MobileAPI / Inflow?TenantId = 1234& SalesPersonId = 22

然后以json格式获取数据



现在我想创建一个与Web DB同步的Post方法。

 string JsonString = Inventory(); 





我需要将此json字符串与TenantId一起传递。

我想通过我的URL发布此内容,例如

 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)
});
}



我没有得到如何开始,所以任何人都可以帮助我。



我尝试了什么:



我通过阅读一些谷歌文章尝试了这一点,但仍然不是很好....

 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;
}





和我的网络API代码是

 [HttpPost] 
[AcceptVerbs(POST)]
public HttpResponseMessage Inventory(long TanantId,[FromBody] string JsonInventory)
{
try
{
列表<库存> lstInventory = JsonConvert.DeserializeObject< List< Inventory>>(JsonInventory);
foreach(lstInventory中的var项)
{

}
返回新的HttpResponseMessage(HttpStatusCode.OK);
}
catch(exception ex)
{
throw ex;
}
}





我的库存模型是这个



公共类库存
{
公共字符串ItemId {get;组; }
public string Category {get;组; }
公共小数Price1 {get;组; }
public string说明{get;组; }
public int QuantityAvailable {get;组; }
public int QuantityOnHand {get;组; }
公共字符串方法{get;组; }
}





i很难从窗口应用程序中调用此URL甚至我的Web应用程序也处于运行模式。

解决方案

你很接近! :)

 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: HttpClient 类不应该使用块包裹在中:

您使用的是HttpClient错误,它会破坏您的软件稳定性ASP.NET Monsters [ ^ ]





 catch(exception ex)
{
throw ex;
}



不要那样做!你刚刚销毁了堆栈跟踪,这将无法追踪错误的来源。



如果你真的必须重新抛出异常,没有将它包装在一个新的异常中,只需使用 throw; ,不要 ex

< pre lang =C#> catch (例外情况)
{
// 在这里做一些例外...
throw ;
}



但是在这种情况下,由于你没有做任何异常,只需删除 try..catch block。


您可以在客户端代码中使用以下几种方法:



1使用开箱即用的nuget包,例如RestSharp。这允许您根据HTTP 1.1规范调用支持的动词的任何HTTP请求。该库具有RestClient和RestRequest类。请参阅 RestSharp - 用于.NET的简单REST和HTTP客户端的文档[ ^ ]。



2.使用内置的.NET框架类型,如WebClient,或HttpWebRequest。理查德建议的解决方案就是使用WebClient的解决方案。



此外,我注意到在Web API(服务器)代码中,您使用序列化字符串作为参数来自身体 - JsonInventory。但是,您可以直接在此处使用Inventory类型,而无需使用Newtonsoft.Json库显式反序列化。实际上,ASP.NET Web API负责处理它。


感谢您的解决方案,但我已经解决了....我的代码是



 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;

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

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





和我这样的网络API代码



 [HttpPost] 
[AcceptVerbs(POST)]
async public Task Inventory(long TenantId)
{
try
{
byte [] data = await Request.Content.ReadAsByteArrayAsync();
string JsonInventory = System.Text.Encoding.Default.GetString(data);
列表<库存> lstInventory = JsonConvert.DeserializeObject< List< Inventory>>(JsonInventory);
foreach(lstInventory中的var项目)
{

}

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





公共类库存
{
public string ItemId {get;组; }
public string Category {get;组; }
公共小数Price1 {get;组; }
public string说明{get;组; }
public int QuantityAvailable {get;组; }
public int QuantityOnHand {get;组; }
公共字符串方法{get;组; }
}


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.

解决方案

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:

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.


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.


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; }
   }


这篇关于如何制作post方法并从我的桌面应用程序中调用它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆