zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    C# 保存文件到数据库
    4.Linq To Xml操作XML增删改查
    服务器端包含 SSI简介
    htm、html、shtml网页区别
    localStorage使用总结
    jquery.cookie.js——jquery的cookie插件
    javascript:;与javascript:void(0)使用介绍
    JS中函数void()
    gitlab使用 —— 多人协同工作(重要技能)
    cookie、localstroage与sessionstroage的一些优缺点
  • 原文地址:https://www.cnblogs.com/1285026182YUAN/p/15246829.html
Copyright © 2011-2022 走看看