• NETCORE


    NETCORE - 调用第三方接口

    调用方式: WebApi 

    创建两个 NetCore WebApi 项目 ,框架:.net5

     1) 项目:NETCORE.ConSul

     2) 项目:NETCORE.ConSul.Service

    一. 项目 NETCORE.ConSul.Service

    1.  新建接口

    namespace NETCORE.Consul.Service.Controllers
    {
        [Route("api/[controller]")]
        [ApiController]
        public class PenController : ControllerBase
        {
            //测试接口
            [Route("GetPenInfo")]
            [HttpGet]
            public string GetPenInfo()
            {
                Task.Run(() => { Console.WriteLine($" get a new pen , Host: {0}", HttpContext.Request.Host.Value); });
                return "success! get a new pen !";
            }
        }
    }

    2. 修改IP地址与端口:

    路径:Properties / launchSettings.json

    {
      "iisSettings": {
        "windowsAuthentication": false,
        "anonymousAuthentication": true,
        "iisExpress": {
          "applicationUrl": "http://localhost:24384",
          "sslPort": 44335
        }
      },
      "$schema": "http://json.schemastore.org/launchsettings.json",
      "profiles": {
        "IIS Express": {
          "commandName": "IISExpress",
          "launchBrowser": true,
          "launchUrl": "swagger",
          "environmentVariables": {
            "ASPNETCORE_ENVIRONMENT": "Development"
          }
        },
        "NETCORE.Consul.Service": {
          "commandName": "Project",
          "launchBrowser": true,
          "launchUrl": "swagger",
          "environmentVariables": {
            "ASPNETCORE_ENVIRONMENT": "Development"
          },
          "dotnetRunMessages": "true",
          "applicationUrl": "https://10.10.50.99:5055;http://10.10.50.99:5056",
          "jsWebView2Debugging": true
        }
      }
    }

     3. 调试

    接口访问地址:https://10.10.50.99:5055/api/Pen/GetPenInfo

     

     二. 项目 NETCORE.Consul

    1.  修改IP地址与端口:

    路径:Properties / launchSettings.json

    {
      "iisSettings": {
        "windowsAuthentication": false,
        "anonymousAuthentication": true,
        "iisExpress": {
          "applicationUrl": "http://10.10.50.99:19691",
          "sslPort": 44328
        }
      },
      "$schema": "http://json.schemastore.org/launchsettings.json",
      "profiles": {
        "IIS Express": {
          "commandName": "IISExpress",
          "launchBrowser": true,
          "launchUrl": "swagger",
          "environmentVariables": {
            "ASPNETCORE_ENVIRONMENT": "Development"
          }
        },
        "NETCORE.ConSul": {
          "commandName": "Project",
          "launchBrowser": true,
          "launchUrl": "swagger",
          "environmentVariables": {
            "ASPNETCORE_ENVIRONMENT": "Development"
          },
          "dotnetRunMessages": "true",
          "applicationUrl": "https://10.10.50.99:5001;http://10.10.50.99:5000"
        }
      }
    }

     2. 注入 HTTPClient

    在 startup.cs 中修改 ConfigureServices 方法 

            public void ConfigureServices(IServiceCollection services)
            {
                //用于调用博客园接口
                services.AddHttpClient("ServiceBlogs", x =>
                {
                    x.BaseAddress = new Uri("https://www.cnblogs.com");
                    x.DefaultRequestHeaders.Add("Cache-Control", "no-cache");
                });
                //用于调用Service1接口
                services.AddHttpClient("ServiceService1", x =>
                {
                    x.BaseAddress = new Uri("https://10.10.50.99:5055");
                    x.DefaultRequestHeaders.Add("Cache-Control", "no-cache");
                }).ConfigurePrimaryHttpMessageHandler(() =>//防止报ssl错误
                {
                    return new HttpClientHandler()
                    {
                        ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
                    };
                });
    services.AddControllers(); services.AddSwaggerGen(c
    => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "NETCORE.ConSul", Version = "v1" }); }); }

    3. 新增接口

    namespace NETCORE.ConSul.Controllers
    {
        [Route("api/[controller]")]
        [ApiController]
        public class BookController : ControllerBase
        {
            IHttpClientFactory _clientFactory;
            public BookController(IHttpClientFactory clientFactory)
            {
                _clientFactory = clientFactory;
            }
    
            [Route("CallPen")]
            [HttpPost]
            public async Task<IActionResult> CallPen()
            {
                var client = _clientFactory.CreateClient("ServiceService1");//必须与startup里面注入的名称对应
                //var content = new StringContent("");
                //content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
                var response = await client.GetAsync("api/pen/GetPenInfo");
                var sss = response.Content.ReadAsStringAsync().Result; 
                return Ok(sss); 
            }
        }
    }

    4. 调用接口

     


    项目:NETCORE.ConSul

    项目:NETCORE.ConSulService
    附代码:https://gitee.com/wuxincaicai/NETCORE.git

  • 相关阅读:
    把数据库转化成数据库脚本
    营养瘦身第一菜——金陵素什锦 健康程序员,至尚生活!
    十类好吃不胖的食物 健康程序员,至尚生活!
    一周带饭实录(附作菜菜谱) 健康程序员,至尚生活!
    日常五大习惯有助减肥 健康程序员,至尚生活!
    【暴强】200种好口碑便宜护肤品 健康程序员,至尚生活!
    腹式肠道操 缩胃瘦身有奇效 健康程序员,至尚生活!
    一天4时段喝水轻松瘦身 健康程序员,至尚生活!
    10种不要钱的护肤法则 健康程序员,至尚生活!
    看了这篇你肯定瘦 全身上下想瘦哪就瘦哪 健康程序员,至尚生活!
  • 原文地址:https://www.cnblogs.com/1285026182YUAN/p/15246829.html
Copyright © 2020-2023  润新知