WebAPI-HTTP编程模型

带着问题去思考,大家好!
它是什么?它包含什么?它能干什么?

消息

HTTP编程模型的核心就是消息抽象,表示为:HttPRequestMessage,HttpResponseMessage.用于客户端和服务端之间交换请求和响应消息。

HttpMethod类包含了一组静态属性:

复制代码
   private static readonly HttpMethod getMethod = new HttpMethod("GET");

        private static readonly HttpMethod putMethod = new HttpMethod("PUT");

        private static readonly HttpMethod postMethod = new HttpMethod("POST");

        private static readonly HttpMethod deleteMethod = new HttpMethod("DELETE");

        private static readonly HttpMethod headMethod = new HttpMethod("HEAD");

        private static readonly HttpMethod optionsMethod = new HttpMethod("OPTIONS");

        private static readonly HttpMethod traceMethod = new HttpMethod("TRACE")
复制代码

标头

  • HttpRequestHeaders:包含请求标头
  • HttpResponseHeaders:包含响应标头
  • HttpContentHeaders:包含内容标头

 

消息内容

HttpContent包含了非虚拟公共方法

  • Task<string> ReadAsStringAsync()
  • Task<byte[]> ReadAsByteArrayAsync()
  • Task<Stream> ReadAsStreamAsync()
  • Task CopyToAsync(Stream stream, TransportContext context)

第一种方式用于推送方式访问原始的消息内容。将一个流传递给CopyAsync方法,然后把消息内容推送到这个流中

复制代码
using(car client=new HtppClient())
{
    var response=
          await client.GetAsync("",HttpCompletionOption.ResponseHeadersRead);
response.EnsureSuccessStatusCode();
var ms=new MemorySteam();
await response.Content.CopyToAsync(ms);
Assert.True(ms.Length>0);
}
复制代码

也可以使用ReadAsStreamAsync().拉取方式访问。这个方法异步返回一个流

复制代码
            using(var client=new HttpClient())
            {
                var response = await client.GetAsync("");
                response.EnsureSuccessStatusCode();
                var steam = await response.Content.ReadAsStreamAsync();
                var buffer = new byte[2 * 1024];
                var len = await steam.ReadAsync(buffer, 0, buffer.Length);
               
            }
复制代码

ReadAsStringAsync和ReadAsByteArrayAsync-异步提供消息内容的缓冲副本。ReadAsStringAsync返回原始的字节内容,ReadAsByteArrayAsync将内容解码为字符串返回

当然也可以扩展为

public override Task<object> ReadContentAsync(HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters, IFormatterLogger formatterLogger)

 

posted @   梦一回  阅读(497)  评论(0编辑  收藏  举报
编辑推荐:
· 对象命名为何需要避免'-er'和'-or'后缀
· SQL Server如何跟踪自动统计信息更新?
· AI与.NET技术实操系列:使用Catalyst进行自然语言处理
· 分享一个我遇到过的“量子力学”级别的BUG。
· Linux系列:如何调试 malloc 的底层源码
阅读排行:
· C# 中比较实用的关键字,基础高频面试题!
· .NET 10 Preview 2 增强了 Blazor 和.NET MAUI
· Ollama系列05:Ollama API 使用指南
· 为什么AI教师难以实现
· 如何让低于1B参数的小型语言模型实现 100% 的准确率
点击右上角即可分享
微信分享提示