it编程 > 编程语言 > Asp.net

C#控制台程序同步调用WebApi实现方式

29人参与 2025-08-12 Asp.net

控制台程序一般当作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;
        }
    }
}

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。

(0)

您想发表意见!!点此发布评论

推荐阅读

C#实现磁盘空间实时预警监控功能

08-12

C# Opacity 不透明度的具体使用

08-13

C# Serilog 日志的使用小结

08-13

C#中SortedSet的具体使用

08-13

使用c#进行串口通信的实现示例

08-13

visual studio 如何升级更新版本

08-11

猜你喜欢

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论