.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

相关推荐
工业甲酰苯胺4 分钟前
Spring Boot 整合 MyBatis 的详细步骤(两种方式)
spring boot·后端·mybatis
新知图书36 分钟前
Rust编程的作用域与所有权
开发语言·后端·rust
wn5312 小时前
【Go - 类型断言】
服务器·开发语言·后端·golang
希冀1232 小时前
【操作系统】1.2操作系统的发展与分类
后端
GoppViper2 小时前
golang学习笔记29——golang 中如何将 GitHub 最新提交的版本设置为 v1.0.0
笔记·git·后端·学习·golang·github·源代码管理
爱上语文3 小时前
Springboot的三层架构
java·开发语言·spring boot·后端·spring
serve the people3 小时前
springboot 单独新建一个文件实时写数据,当文件大于100M时按照日期时间做文件名进行归档
java·spring boot·后端
罗政9 小时前
[附源码]超简洁个人博客网站搭建+SpringBoot+Vue前后端分离
vue.js·spring boot·后端
拾光师10 小时前
spring获取当前request
java·后端·spring
Java小白笔记12 小时前
关于使用Mybatis-Plus 自动填充功能失效问题
spring boot·后端·mybatis