.NET HttpClient

环境搭建

服务注册

builder.Services.AddHttpClient();

创建实体类

csharp 复制代码
namespace HttpClient
{
    public class RequestModel
    {
        public string userName { set; get; }
        public string password { set; get; }

    }

    public class ApiResult
    {
        bool IsSuccess { set; get; }

        object Result { set; get; }

        string Msg { set; get; }
    }
}

创建服务提供类

csharp 复制代码
using Microsoft.AspNetCore.Mvc;

namespace HttpClient.Controllers
{
    [ApiController]
    [Route("[controller]/[action]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };

        private readonly ILogger<WeatherForecastController> _logger;

        public WeatherForecastController(ILogger<WeatherForecastController> logger)
        {
            _logger = logger;
        }

        [HttpGet]
        public IEnumerable<WeatherForecast> Get()
        {
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = Random.Shared.Next(-20, 55),
                Summary = Summaries[Random.Shared.Next(Summaries.Length)]
            })
            .ToArray();
        }

        [HttpPost]
        public object Post([FromBody] RequestModel model)
        {
            return model;

        }
    }
}

测试

ini 复制代码
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using System.Text;
using System.Text.Json;
using static System.Net.Mime.MediaTypeNames;

namespace HttpClient.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class Demo : ControllerBase
    {

        private readonly IHttpClientFactory _httpClientFactory;

        public Demo(IHttpClientFactory httpClientFactory)
        {
            _httpClientFactory = httpClientFactory;
        }

        [HttpPost]
        public async Task<string> Post()
        {
            RequestModel req = new RequestModel
            {
                userName = "zhangsan",
                password = "password",
            };
            // 包装参数
            StringContent stringContent = new StringContent(
                JsonSerializer.Serialize(req),
                Encoding.UTF8,
                Application.Json
                );
            System.Net.Http.HttpClient httpClient = _httpClientFactory.CreateClient();
            using var response = await httpClient.PostAsync("https://localhost:7038/WeatherForecast/Post", stringContent);
            var task = response.Content.ReadAsStringAsync();
            return await task;
        }


        [HttpGet]
        public async Task<string> Get()
        {
            HttpRequestMessage httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, "https://localhost:7038/WeatherForecast/Get")
            {
                Headers =
                {
                    // 设置请求头
                }
            };

            var client = _httpClientFactory.CreateClient();
            HttpResponseMessage httpResponseMessage = client.Send(httpRequestMessage);
            if (httpResponseMessage.IsSuccessStatusCode)
            {
                var result = await httpResponseMessage.Content.ReadAsStringAsync();
                 return result;
            }
            else
            {
                return "请求失败";
            }
        }
    }
}

调用HttpGet

调用HttpPost

相关推荐
何中应18 分钟前
Spring Boot中选择性加载Bean的几种方式
java·spring boot·后端
web2u1 小时前
MySQL 中如何进行 SQL 调优?
java·数据库·后端·sql·mysql·缓存
michael.csdn1 小时前
Spring Boot & MyBatis Plus 版本兼容问题(记录)
spring boot·后端·mybatis plus
Ciderw2 小时前
Golang并发机制及CSP并发模型
开发语言·c++·后端·面试·golang·并发·共享内存
Мартин.2 小时前
[Meachines] [Easy] Help HelpDeskZ-SQLI+NODE.JS-GraphQL未授权访问+Kernel<4.4.0权限提升
后端·node.js·graphql
程序员牛肉2 小时前
不是哥们?你也没说使用intern方法把字符串对象添加到字符串常量池中还有这么大的坑啊
后端
烛阴2 小时前
Go 语言进阶必学:&^ 操作符,高效清零的秘密武器!
后端·go
网络风云2 小时前
golang中的包管理-下--详解
开发语言·后端·golang
京东零售技术3 小时前
一次线上生产库的全流程切换完整方案
后端
我们的五年3 小时前
【C语言学习】:C语言补充:转义字符,<<,>>操作符,IDE
c语言·开发语言·后端·学习