如何避免C#中的http响应超时异常 [英] How to avoid http response timeout exception in C#

查看:274
本文介绍了如何避免C#中的http响应超时异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我通过桌面应用程序中的url调用此函数





I am calling this function via url from my desktop application

[HttpPost]
        [AcceptVerbs("POST")]
        async public Task<HttpResponseMessage> SyncItem(long TenantId)
        {
            try
            {
                CashVitae_TM.Tenant oTenant = new CashVitae_TM.Tenant();
                oTenant = oTenant.getTenantByTenantId(TenantId);

                string dbUN = oTenant.DBUN;
                string dbPass = oTenant.DBPass;

                long SavedItemId = 0;
                Item oitem = new Item();
                
                byte[] data = await Request.Content.ReadAsByteArrayAsync();
                string JsonInventory = System.Text.Encoding.Default.GetString(data);
                List<InventoryItem> lstInventoryItem = JsonConvert.DeserializeObject<List<InventoryItem>>(JsonInventory);
                foreach (var Inventory in lstInventoryItem)
                {
                    Item oitem1 = new Item();
                    string ItemCode = Inventory.ItemCode;
                    Item item = oitem.getItembyCode(TenantId, dbUN, dbPass, ItemCode);
                    if (item != null)
                    {
                        oitem1.Id = item.Id;
                        oitem1.Code = item.Code;
                        oitem1.CreatedDtTm = item.CreatedDtTm;
                    }
                    else
                    {
                        oitem1.Id = 0;
                        oitem1.Code = Inventory.ItemCode;
                        oitem1.CreatedDtTm = DateTime.Now;
                    }
                    oitem1.TenantId = TenantId;
                    oitem1.Name = Inventory.Name;
                    oitem1.Category = Convert.ToString(Inventory.Category);
                    oitem1.CostMethod = Convert.ToString(Inventory.MethodName);
                    oitem1.Location = Convert.ToString(Inventory.Location);
                    oitem1.UnitPrice = Inventory.UnitPrice;
                    oitem1.Quantity = Inventory.QtyAvailable;
                    oitem1.QtyOnHand = Inventory.QtyOnHand;
                    oitem1.IsActive = Inventory.IsActive;
                    oitem1.ModifiedDtTm = DateTime.Now;
                    SavedItemId = oitem1.Save(TenantId, dbUN, dbPass);
                }   
                return new HttpResponseMessage(HttpStatusCode.OK);
            }
            catch (Exception ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message);
            }
        }





这是我的桌面应用程序代码



and this my desktop application code

try
                        {
                            string str = Inventory();
                            using (WebClient httpclient = new WebClient())
                            {
                                //string str = "abc";
                                string url = "http://localhost:51411/api/MobileAPI/SyncItem?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);
                                }
                                request.Timeout = Timeout.Infinite;
                                request.KeepAlive = true;
                                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                                response.StatusCode.ToString();
                            }
                        }
                        catch(Exception ex)
                        {
                            throw ex;
                        }





但是我的操作在我的桌面上有超时异常



我尝试过:



我在我的API中调用一种方法来保存数据库中的数据

我试过



but i am getting operation has timeout exception in my desktop

What I have tried:

I am calling a method in my API to save data in web DB
I tried

request.Timeout = Timeout.Infinite;
                                request.KeepAlive = true;





然后我也得到同样的错误,我怎么能处理超时异常。 />
一个解决方案我知道拆分数据但是如果有人可以提供没有拆分数据的其他解决方案,只有一次我想发送整个数据。



then also same error i am getting, how i can handle timeout exception.
one solution I know that split data but if anyone can give else solution without split data, only once i want to send whole data.

推荐答案

非常基本的异常处理可以解决您的问题。



Very basic Exception handling can be one of the solutions of your problem.

try
{
   using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
   {
      WebHeaderCollection headers = response.Headers;    
      using (Stream answer = response.GetResponseStream())
      {
          // Do stuff
      }
   }
}
catch (WebException e)
{
   if (e.Status == WebExceptionStatus.Timeout)
   {
      // Handle timeout exception
   }
   else throw;
}


这篇关于如何避免C#中的http响应超时异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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