欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 教育 > 高考 > (六)WebAPI方法的调用

(六)WebAPI方法的调用

2025/2/25 2:06:45 来源:https://blog.csdn.net/ccysjy/article/details/142165752  浏览:    关键词:(六)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]等特性,用于从路由参数、表单数据等位置获取参数值。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com