C#控制臺程序同步調(diào)用WebApi實現(xiàn)方式
控制臺程序一般當(dāng)作Job使用,有時候需要控制臺程序調(diào)用WebApi返回結(jié)果后才能執(zhí)行下一步動作,否則會出錯,所以這個時候就需要同步處理。
關(guān)于異步調(diào)用還是同步調(diào)用的相關(guān)說明這里不做詳細闡述,請自行查找資料。
如果是異步就會報錯如下:
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.<—
同步調(diào)用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);/*編碼轉(zhuǎn)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("程序處理出錯,請盡快聯(lián)系管理員處理!"+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;
}
}
}總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
C#如何優(yōu)雅地取消進程的執(zhí)行之Cancellation詳解
本文介紹了.NET框架中的取消協(xié)作模型,包括CancellationToken的使用、取消請求的發(fā)送和接收、以及如何處理取消事件2024-12-12
C#創(chuàng)建及訪問網(wǎng)絡(luò)硬盤的實現(xiàn)
本文主要介紹了C#創(chuàng)建及訪問網(wǎng)絡(luò)硬盤的實現(xiàn),文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-03-03
C#使用Data?Annotations進行手動數(shù)據(jù)驗證
這篇文章介紹了C#使用Data?Annotations進行手動數(shù)據(jù)驗證的方法,文中通過示例代碼介紹的非常詳細。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-06-06

