HttpWebRequest 改为 HttpClient 踩坑记-请求头设置

HttpWebRequest 改为 HttpClient 踩坑记-请求头设置

Intro

这两天改了一个项目,原来的项目是.net framework 项目,里面处理 HTTP 请求使用的是 WebReauest,但是 WebRequest 已经不再推荐使用了,你如果在项目中使用的话,编译器会警告, WebRequest已过时,新项目要 .Net standard 重写就直接 HttpClient 来处理 HTTP 请求了,在改的过程中踩了几个坑,记录一下

请求头处理

HttpClient 通常如果要添加请求头的话。一般这样添加:

 var requestMessage = new HttpRequestMessage(_httpMethod, requestUrl)
 {
       Content = new StringContent(postData, Encoding.UTF8, "appplication/json")
 };
 //
requestMessage.Headers.TryAddWithoutValidation("Date", date);

但是有些请求头这样加是可以的,但是有些请求头就不行了,这次就遇到了两个例外,一个是 Content-Type,一个是 Content-MD5 这两个请求头。

设置请求头 Content-Type

正确姿势:

requestMessage.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue(ContentType);

设置请求头 Content-MD5

正确姿势:

requestMessage.Content.Headers.TryAddWithoutValidation("Content-MD5", contentMD5);

More

那么都有哪些请求头是属于 Content 呢,来看这里:

参考来源:

        private static readonly string[] s_wellKnownContentHeaders = {
            HttpKnownHeaderNames.ContentDisposition,
            HttpKnownHeaderNames.ContentEncoding,
            HttpKnownHeaderNames.ContentLanguage,
            HttpKnownHeaderNames.ContentLength,
            HttpKnownHeaderNames.ContentLocation,
            HttpKnownHeaderNames.ContentMD5,
            HttpKnownHeaderNames.ContentRange,
            HttpKnownHeaderNames.ContentType,
            HttpKnownHeaderNames.Expires,
            HttpKnownHeaderNames.LastModified
        };

Reference

  • https://stackoverflow.com/questions/22256470/cannot-set-content-md5-header-in-webapi-response
  • https://stackoverflow.com/questions/10679214/how-do-you-set-the-content-type-header-for-an-httpclient-request?rq=1

你可能感兴趣的:(HttpWebRequest 改为 HttpClient 踩坑记-请求头设置)