欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

WebAPI-HTTP编程模型

程序员文章站 2022-06-19 23:42:36
带着问题去思考,大家好!它是什么?它包含什么?它能干什么? 消息 HTTP编程模型的核心就是消息抽象,表示为:HttPRequestMessage,HttpResponseMessage.用于客户端和服务端之间交换请求和响应消息。 HttpMethod类包含了一组静态属性: private stat ......

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

消息

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)