当前位置: 首页 > news >正文

(六)WebAPI方法的调用

1.WebAPI中定义的GET、POST方法
        [HttpGet(Name = "GetWeatherForecast")]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 string Post([FromBody] WeatherForecast message, [FromQuery] string param){//定义json格式返回结果var result = new { code = 0, city = param, data = message };return JsonConvert.SerializeObject(result);//return JsonSerializer.Serialize(result);}
2. WebAPI方法的调用

创建一个控制台应用程序,分别发送GET、POST请求。

// See https://aka.ms/new-console-template for more informationusing System;
using System.Text;
using System.Text.Json;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net;internal class Program
{private static async Task Main(string[] args){//GET请求string url2 = $"http://localhost:5003/api/WeatherForecast/get";httpResponse(url2, "", "GET");//POST请求string param = "北京";string url = $"http://localhost:5003/api/WeatherForecast/post?param={Uri.EscapeDataString(param)}";var weather = new{Date = "2024-09-14T16:41:37.2488358+08:00",TemperatureC = 18,Summary = "温暖"};string content = JsonSerializer.Serialize(weather);httpResponse(url, content, "POST");Console.ReadLine();}private static async void httpResponse(string url, string message,string type = ""){//调用CoreWebAPI项目中的Post方法using (var client = new HttpClient()){var content = new StringContent(message, Encoding.UTF8, "application/json");Console.WriteLine("Sending request...");Console.WriteLine($"URL: {url}\r\n ");// 发送请求  var response = new HttpResponseMessage();if (type.ToUpper() == "POST") {response = await client.PostAsync(url, content);}else if (type.ToUpper() == "GET"){response = await client.GetAsync(url);}// 读取响应内容  if (response.IsSuccessStatusCode){string responseBody = await response.Content.ReadAsStringAsync();Console.WriteLine("Request succeeded:");Console.WriteLine(responseBody);}else{Console.WriteLine("Request failed:");Console.WriteLine($"Status Code: {response.StatusCode}");string responseBody = await response.Content.ReadAsStringAsync();Console.WriteLine($"Response Body: {responseBody}");}}}
}
3.参数特性[FromBody]、[FromBody]

在ASP.NET Core Web API中,[FromBody][FromQuery]是两种常用的参数绑定特性(Attributes),它们分别用于控制参数值从HTTP请求的哪个部分获取。这对于编写清晰、易于理解的API接口非常重要。

1. [FromBody] 标记的参数

当使用[FromBody]特性时,参数值会从请求的Body部分读取。这通常用于处理JSON或XML格式的复杂数据类型。[FromBody]通常只能应用于一个参数,因为HTTP请求的Body通常只包含一次性的数据块,ASP.NET Core会尝试将整个Body反序列化为指定的类型。

如何传参

  • 客户端请求:通常,你需要通过HTTP POST或PUT请求发送JSON或XML格式的数据到服务器的Body部分。

  • 示例

    假设你有一个API接口,期望接收一个用户对象作为参数。

  • [HttpPost]  
    public IActionResult CreateUser([FromBody] User user)  
    {  // 处理用户对象  
    }

    客户端发送的HTTP请求体(以JSON为例)可能如下:

  • {  "name": "John Doe",  "email": "johndoe@example.com"  
    }

    2. [FromQuery] 标记的参数

    [FromQuery]特性用于从请求的URL的查询字符串中获取参数值。这对于简单的键值对参数特别有用,如分页参数、搜索过滤器等。

    如何传参

  • 客户端请求:在请求的URL后面添加查询字符串,格式为?paramName=value

  • 示例

    假设你有一个API接口,需要分页获取用户列表,接口期望接收页码和每页显示条数作为参数。

  • [HttpGet]  
    public IActionResult GetUsers([FromQuery] int page = 1, [FromQuery] int pageSize = 10)  
    {  // 处理分页逻辑  
    }

    客户端请求的URL可能如下:

  • https://yourapi.com/api/users?page=2&pageSize=5

    注意事项

  1. 当你使用[FromBody]时,请确保请求的Content-Type头部被正确设置(如application/json),以便ASP.NET Core能够正确地解析请求体。
  2. 通常,一个请求只能有一个[FromBody]参数,因为HTTP请求的Body是流式的,一旦被读取就无法再次读取。
  3. [FromQuery]参数可以从URL的查询字符串中读取多个参数,非常适合处理简单的GET请求。
  4. 除了[FromBody][FromQuery],ASP.NET Core还提供了[FromRoute][FromForm]等特性,用于从路由参数、表单数据等位置获取参数值。

http://www.mrgr.cn/news/30344.html

相关文章:

  • 学习风格的类型
  • Scrapy爬虫框架 Pipeline 数据传输管道
  • 多线程---线程的状态及常用方法
  • 【9.11最新发布】Win11 24H2 26100.1742 专业版镜像!
  • 解决 Torch not compiled with CUDA enabled 问题 | MiniCPM3-4B 【应用开发笔记】
  • 阅读笔记——《围城》
  • 前后端分离项目中如何保证 API 安全
  • Vue3.0组合式API:computed计算属性、watch监听器、watchEffect高级监听器
  • 小阿轩yx-SaltStack部署与应用基础
  • ABAP-Logger ABAP 日志记录与任何其他语言一样轻松
  • 聊一聊测试用例的重要性
  • PathoDuet: HE 和 IHC 染色病理切片分析的基础模型|文献速递-Transformer架构在医学影像分析中的应用
  • 高校宿舍电费管理怎么实现
  • 【论文阅读】Face2Diffusion for Fast and Editable Face Personalization
  • MySQL数据库
  • Linux服务器本地部署Joplin Server并实现手机电脑多端同步文档
  • Python PDF转图片自定义输出
  • redis为什么不使用一致性hash
  • 算法:双指针题目练习
  • 使用Postman轻松搞定文件上传测试