web Api 自定义请求头

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zjlovety/article/details/39521453

1、如果要自定义请求头,我们需要继承一个类:HttpClientHandler 

     public class GitHttpClientHandler:HttpClientHandler

复制代码
    {
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            request.Headers.Referrer = new Uri("http://www.google.com/");
            request.Headers.Add("UserAgent""Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727)");
            
            Task<HttpResponseMessage> task = base.SendAsync(request, cancellationToken);
            HttpResponseMessage response = task.Result;
            MediaTypeHeaderValue contentType = response.Content.Headers.ContentType;
            if (string.IsNullOrEmpty(contentType.CharSet))
            {
                contentType.CharSet = "GBK";
            }
            return task;
        }
    }

 MediaTypeHeaderValue contentType = response.Content.Headers.ContentType.MediaType = "application/json";
            contentType.MediaType = "application/json";
复制代码
阅读更多

没有更多推荐了,返回首页