.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

相关推荐
库库林_沙琪马11 分钟前
REST接口幂等设计深度解析
spring boot·后端
IT_陈寒14 分钟前
Redis性能提升50%的7个关键优化策略,90%开发者都不知道第5点!
前端·人工智能·后端
智商偏低19 分钟前
ASP.NET Core 身份验证概述
后端·asp.net
冷冷的菜哥20 分钟前
ASP.NET Core使用MailKit发送邮件
后端·c#·asp.net·发送邮件·mailkit
canonical_entropy38 分钟前
XDef:一种面向演化的元模型及其构造哲学
后端
小林coding1 小时前
再也不怕面试了!程序员 AI 面试练习神器终于上线了
前端·后端·面试
lypzcgf1 小时前
Coze源码分析-资源库-删除插件-后端源码-错误处理与总结
人工智能·后端·go·coze·coze源码分析·ai应用平台·agent平台
文心快码BaiduComate1 小时前
WAVE SUMMIT深度学习开发者大会2025举行 文心大模型X1.1发布
前端·后端·程序员
SamDeepThinking1 小时前
在Windows 11上配置Cursor IDE进行Java开发
后端·ai编程·cursor
知其然亦知其所以然1 小时前
面试官微笑发问:第100万页怎么查?我差点当场沉默…
后端·mysql·面试