.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

相关推荐
IT_陈寒1 小时前
Redis缓存雪崩把我坑惨了,这次长记性了
前端·人工智能·后端
LucianaiB1 小时前
用 WorkBuddy 研究腾讯、阿里和 DeepSeek,我没敢直接说「AI 很赚钱」
后端
用户8356290780511 小时前
使用 Python 管理 PDF 属性和元数据
后端·python
分支预测失败2 小时前
RISC-V 上下文切换实战:从 Trap 入口到 Linux 进程调度
后端·嵌入式
用户8356290780512 小时前
使用 Python 在 Word 文档中创建自定义图表
后端·python
Profile排查笔记3 小时前
JavaScript 实现浏览器指纹生成:基础字段、Canvas 采样与 SHA-256 摘要
前端·人工智能·后端·自动化
GoGeekBaird3 小时前
我给 DeepSeek Harness 造了个铸造台
后端
YOU OU3 小时前
Spring Cloud概述
后端·spring·spring cloud
半个落月3 小时前
React JWT 登录鉴权实战:Mock、Zustand、Axios 与路由守卫全流程
后端·react.js
XingXingXxx3 小时前
Skill 能自己变强吗?从轨迹归纳到文本空间优化的进化之路
后端