C#控制臺(tái)程序同步調(diào)用WebApi實(shí)現(xiàn)方式
控制臺(tái)程序一般當(dāng)作Job使用,有時(shí)候需要控制臺(tái)程序調(diào)用WebApi返回結(jié)果后才能執(zhí)行下一步動(dòng)作,否則會(huì)出錯(cuò),所以這個(gè)時(shí)候就需要同步處理。
關(guān)于異步調(diào)用還是同步調(diào)用的相關(guān)說(shuō)明這里不做詳細(xì)闡述,請(qǐng)自行查找資料。
如果是異步就會(huì)報(bào)錯(cuò)如下:
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"];/*帳號(hào)*/
string Password = ConfigurationManager.AppSettings["Password"];/*密碼*/
string base64Auth = UserID + ":" + Password; /*合并帳號(hào)密碼*/
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是新建的類(lèi)測(cè)試API是否暢通*/
if (!status.Contains("200"))
{
logger.Error(url + "無(wú)法訪問(wèn)!********" + status.ToString() + "**********End:" + DateTime.Now.ToString() + "******************");
return;
}
}
catch (Exception Msg)
{
logger.Error("程序處理出錯(cuò),請(qǐng)盡快聯(lián)系管理員處理!"+Msg);
logger.Info("******************End:" + DateTime.Now.ToString() + "******************");
return;
}
}
}
}Cls001類(lèi)里面的寫(xiě)法
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;
/*該方法為同步請(qǐng)求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); /*這里請(qǐng)求時(shí)用到同步*/
if (response.IsSuccessStatusCode)
{
result = response.Content.ReadAsStringAsync().Result;
return result;
}
if (!response.IsSuccessStatusCode)
{
result = "Error";
}
}
catch (Exception Msg)
{
logger.Error(Msg);
}
return result;
}
}
}總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
說(shuō)說(shuō)C#的async和await的具體用法
本篇文章主要介紹了說(shuō)說(shuō)C#的async和await的具體用法,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-09-09
C#實(shí)現(xiàn)Excel工作表拆分的項(xiàng)目實(shí)踐
本文介紹了使用 C# 和 Free Spire.XLS 免費(fèi)庫(kù)實(shí)現(xiàn) Excel 工作表拆分的完整方案,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2026-01-01
C#如何優(yōu)雅地取消進(jìn)程的執(zhí)行之Cancellation詳解
本文介紹了.NET框架中的取消協(xié)作模型,包括CancellationToken的使用、取消請(qǐng)求的發(fā)送和接收、以及如何處理取消事件2024-12-12
利用C#實(shí)現(xiàn)繪制出地球旋轉(zhuǎn)效果
這篇文章主要為大家詳細(xì)介紹了如何利用C#語(yǔ)言實(shí)現(xiàn)繪制出地球旋轉(zhuǎn)的效果,文中的示例代碼講解詳細(xì),具有一定的參考價(jià)值,需要的可以了解一下2023-02-02
C#創(chuàng)建及訪問(wèn)網(wǎng)絡(luò)硬盤(pán)的實(shí)現(xiàn)
本文主要介紹了C#創(chuàng)建及訪問(wèn)網(wǎng)絡(luò)硬盤(pán)的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-03-03
C#使用Data?Annotations進(jìn)行手動(dòng)數(shù)據(jù)驗(yàn)證
這篇文章介紹了C#使用Data?Annotations進(jìn)行手動(dòng)數(shù)據(jù)驗(yàn)證的方法,文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-06-06

