C#控制台程序同步调用WebApi方法

  • 控制台程序一般当作Job使用,有时候需要控制台程序调用WebApi返回结果后才能执行下一步动作,否则会出错,所以这个时候就需要同步处理。关于异步调用还是同步调用的相关说明这里不做详细阐述,请自行查找资料。

  • 如果是异步就会报错如下:

System.AggregateException: One or more errors occurred. —>
System.Threading.Tasks.TaskCanceledException: A task was canceled.
— End of inner exception stack trace — at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean
includeTaskCanceledExceptions) at
System.Threading.Tasks.Task1.GetResultCore(Boolean waitCompletionNotification) at System.Threading.Tasks.Task1.get_Result() at
SyncAccounts.Cls001.PostResponse(String url, String postData, String
token) in e:\SyncAccounts\Cls001.cs:line 49 at
SyncAccounts.Program.Main(String[] args) in
e:\SyncAccounts\Program.cs:line 78
—> (Inner Exception #0) System.Threading.Tasks.TaskCanceledException: A task was
canceled.<—


同步调用WebApi方法如下:

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using DataAccessTool;
using System.Web.Script.Serialization;
using log4net;
namespace SyncAccounts
{
    class Program
    {
            static string strConnect = "DB";
            static ILog logger;
            
        static void Main(string[] args)
        {
           try
            {
                string url = ConfigurationManager.AppSettings["url"];    
                string UserID = ConfigurationManager.AppSettings["UserID"];/*帐号*/
                string Password = ConfigurationManager.AppSettings["Password"];/*密码*/
                string base64Auth = UserID + ":" + Password; /*合并帐号密码*/
                System.Text.Encoding encode = System.Text.Encoding.UTF8;
                byte[] bytedata = encode.GetBytes(base64Auth);
                string token = Convert.ToBase64String(bytedata);/*编码转Base64*/
                string postTest = "{\"action\":\"T\"}";
                string status =Cls001.PostResponse(url, postTest, token).Result;/*Cls001是新建的类测试API是否畅通*/
                if (!status.Contains("200"))
                {
                    logger.Error(url + "无法访问!********" + status.ToString() + "**********End:" + DateTime.Now.ToString() + "******************");
                    return;
                }
              }
           catch (Exception Msg)
            {
               logger.Error("程序处理出错,请尽快联系管理员处理!"+Msg);
               logger.Info("******************End:" + DateTime.Now.ToString() + "******************");
               return;
            }
        }
    }
}

Cls001类里面的写法:

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using DataAccessTool;
using System.Web.Script.Serialization;
using log4net;
namespace SyncAccounts
{
    class Cls001
    {
            static ILog logger;
            
            /*该方法为同步请求Api。*/
        public async static Task<string> PostResponse(string url, string postData, string token)
        {
           string result = null;
            try
            {
                if (url.StartsWith("https"))
                System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
                HttpContent httpContent = new StringContent(postData);
                httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                httpContent.Headers.ContentType.CharSet = "utf-8";
                HttpClient httpClient = new HttpClient();
                AuthenticationHeaderValue authValue = new AuthenticationHeaderValue("Basic", token);
                httpClient.DefaultRequestHeaders.Authorization = authValue;
                HttpResponseMessage response = await httpClient.PostAsync(url, httpContent); /*这里请求时用到同步*/
                if (response.IsSuccessStatusCode)
                {
                    result = response.Content.ReadAsStringAsync().Result;
                    return result;
                }
                if (!response.IsSuccessStatusCode)
                {
                    result = "Error";
                }                
            }
            catch (Exception Msg)
            {
                logger.Error(Msg);
            }
            return result;
        }
    }
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值