csharp 对于asp.net WebAPI客户端。启用cookie并以任何方式信任HTTPS认证。
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp 对于asp.net WebAPI客户端。启用cookie并以任何方式信任HTTPS认证。相关的知识,希望对你有一定的参考价值。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net;
using System.Diagnostics;
namespace WebApiSDK
{
public class BaseService
{
private static readonly Lazy<HttpClientHandler> _lazy = new Lazy<HttpClientHandler>(() =>
{
// 為了開啟cookie,讓web api的溝通藉由cookie,而變成stateful。
HttpClientHandler ret = new HttpClientHandler();
ret.CookieContainer = new System.Net.CookieContainer();
ret.ClientCertificateOptions = ClientCertificateOption.Automatic;
return ret;
});
protected static HttpClientHandler _httpClientHandler { get { return _lazy.Value; } }
protected static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
protected HttpClient _http = null;
static BaseService() {
// HTTPS的Certification的問題。
ServicePointManager.ServerCertificateValidationCallback += delegate { return true; };
}
public BaseService(string host) {
Debug.Assert(string.IsNullOrEmpty(host) == false, "host cannot be null.");
if (string.IsNullOrEmpty(host))
{
throw new ArgumentNullException("host");
}
// check final char
char lastCh = host.Last();
if (lastCh.Equals('/') == false && lastCh.Equals('\\') == false)
{
host += "/";
}
_http = new HttpClient(_httpClientHandler);
_http.BaseAddress = new Uri(host);
_http.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
protected TOutput Post<TInput, TOutput>(string requestUrl, TInput input)
{
Uri path = new Uri(_http.BaseAddress, requestUrl);
HttpResponseMessage response = _http.PostAsJsonAsync<TInput>(requestUrl, input).Result;
if (response.IsSuccessStatusCode)
{
return response.Content.ReadAsAsync<TOutput>().Result;
}
log.Debug("Failed, " + response.StatusCode.ToString());
return default(TOutput);
}
protected TOutput Get<TOutput>(string reqeustUrl)
{
Uri path = new Uri(_http.BaseAddress, reqeustUrl);
HttpResponseMessage response = _http.GetAsync(path).Result;
if (response.IsSuccessStatusCode)
{
return response.Content.ReadAsAsync<TOutput>().Result;
}
return default(TOutput);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
namespace WebApiClient
{
public interface IService
{
string HostUrl { get; }
Task<T> HttpGet<T>(string apiUrl) where T : class;
Task<U> HttpPost<T, U>(string apiUrl, T request)
where T : class
where U : class;
}
public class BaseService : IService
{
private static readonly Lazy<HttpClientHandler> _lazy = new Lazy<HttpClientHandler>(() =>
{
// Enable cookies.
HttpClientHandler ret = new HttpClientHandler();
ret.CookieContainer = new System.Net.CookieContainer();
ret.ClientCertificateOptions = ClientCertificateOption.Automatic;
return ret;
});
protected static HttpClientHandler _httpClientHandler { get { return _lazy.Value; } }
static BaseService() {
// For HTTPS Certications.
ServicePointManager.ServerCertificateValidationCallback += delegate { return true; };
}
private HttpClient GetClient()
{
HttpClient client = new HttpClient(_httpClientHandler);
client.BaseAddress = new Uri(this.HostUrl);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
return client;
}
private IService _service = null;
private string _hostUrl = null;
public string HostUrl {
get
{
if (_service != null) {
return _service.HostUrl;
}
return _hostUrl;
}
private set {
_hostUrl = value;
}
}
// For decorate pattern.
public BaseService(IService service) {
_service = service;
}
public BaseService(string hostUrl)
{
_service = null;
this.HostUrl = hostUrl;
}
public virtual async Task<T> HttpGet<T>(string apiUrl) where T : class
{
if (_service != null)
{
T respObj = await _service.HttpGet<T>(apiUrl);
return respObj;
}
using (var client = GetClient())
{
HttpResponseMessage response = await client.GetAsync(apiUrl);
if (response.IsSuccessStatusCode)
{
T respObj = await response.Content.ReadAsAsync<T>();
return respObj;
}
return default(T);
}
}
public virtual async Task<U> HttpPost<T,U>(string apiUrl, T request) where T : class where U : class
{
if (_service != null)
{
U respObj = await _service.HttpPost<T, U>(apiUrl, request);
return respObj;
}
using (var client = GetClient())
{
HttpResponseMessage response = await client.PostAsJsonAsync(apiUrl, request);
if (response.IsSuccessStatusCode)
{
U respObj = await response.Content.ReadAsAsync<U>();
return respObj;
}
return default(U);
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
namespace WSJobClient
{
public class WSBaseClient
{
private string _hostUrl = null;
public WSBaseClient()
{
//! 參考WSJobService裡的Web API Server的設定
SetHostUrl("http://localhost:38360/");
}
//static WSBaseClient() {
// // For HTTPS connection
// ServicePointManager.ServerCertificateValidationCallback += delegate { return true; };
//}
protected void SetHostUrl(string hostUrl)
{
string url = hostUrl.TrimEnd(" \\/".ToCharArray()) + "/";
_hostUrl = url;
}
protected HttpClient GetClient()
{
HttpClient client = new HttpClient();
// configure the client information.
client.BaseAddress = new Uri(_hostUrl);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
return client;
}
protected T POST<U, T>(string apiURL, U request)
{
using (var client = GetClient())
{
using (HttpResponseMessage resp = client.PostAsJsonAsync(apiURL, request).Result)
{
if (resp.IsSuccessStatusCode)
{
T ret = resp.Content.ReadAsAsync<T>().Result;
return ret;
}
return default(T);
}
}
}
protected T GET<T>(string apiURL)
{
using (var client = GetClient())
using (HttpResponseMessage resp = client.GetAsync(apiURL).Result)
{
if (resp.IsSuccessStatusCode)
{
T ret = resp.Content.ReadAsAsync<T>().Result;
return ret;
}
return default(T);
}
}
}
}
以上是关于csharp 对于asp.net WebAPI客户端。启用cookie并以任何方式信任HTTPS认证。的主要内容,如果未能解决你的问题,请参考以下文章
csharp Topshelf + OWIN自主机+ ASP.NET WebAPI + Ninject
csharp 从ASP.NET WebAPI控制器以camelCase格式返回JSON数据。
在 .NET 4.5.1 中发布到 ASP.NET WebApi 2
Asp .Net Core WebApi:异常的第二次http调用