WebHttpBinding _binding = new WebHttpBinding(); WebServiceHost ws = new WebServiceHost(typeof(Service1), new Uri("http://10.10.12.70:8085")); //WebServiceHost ws = new WebServiceHost(typeof(Service1), new Uri("https://10.10.12.70:8085")); //ws.Credentials.ServiceCertificate.SetCertificate("CN",StoreLocation.LocalMachine,StoreName.My); //_binding.Security.Mode = WebHttpSecurityMode.Transport; //_binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None; ws.AddServiceEndpoint(typeof(IService1), _binding, "ss"); ws.Open(); System.Diagnostics.Process.Start("http://10.10.12.70:8085/ss/abc"); MessageBox.Show("ok");
netsh http show sslcert
netsh http add sslcert ipport=0.0.0.0:8085 certhash=50806af07c74f269aad830f7fc536a777ba42d3a appid={BCC1AFD4-E27F-4E74-A162-193069C8437C}
netsh http delete sslcert ipport=0.0.0.0:8085
服务器端代码修改
服务器端的代码修改包括:1)uri的scheme验证,确保资源访问必须采用ssl加密;2)自宿主服务器启动监听uri改为https字头。
scheme验证仍然采用与上篇文章相同的方法,即实现一个新的HttpMessageHandler,并将其注入到消息处理管道中:
public class HttpsGuard : DelegatingHandler { protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { if (!request.RequestUri.Scheme.Equals(Uri.UriSchemeHttps, StringComparison.CurrentCultureIgnoreCase)) { var response = new HttpResponseMessage(HttpStatusCode.BadRequest) { Content = new StringContent("Https is required for security reason") }; return Task.FromResult(response); } return base.SendAsync(request, cancellationToken); } }
修改Startup的Configuration,将上面的HttpMessageHandler注入:
public void Configuration(IAppBuilder app) { // Configure Web API for self-host. var config = new HttpConfiguration(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{action}/{param}", defaults: new { id = RouteParameter.Optional } ); //注入response handler config.MessageHandlers.Add(new ResponseHandler()); //注入httpmessagehandler用于验证request是否均采用SSL加密传输 config.MessageHandlers.Add(new HttpsGuard()); //允许WebApi的跨域访问 - 测试条件下允许所有域的跨域访问 var cors = new EnableCorsAttribute("*", "*", "*"); config.EnableCors(cors); app.UseWebApi(config); }
服务器启动则改为如下:
1 var urlBase = new UriBuilder("HTTPS", ip, 7777).Uri; 2
3 var server = WebApp.Start<Startup>(url: urlBase.AbsoluteUri);
以上三部分修改完成后,对web api服务端代码的修改完毕,可以启动服务,正常开始监听本地7777端口。此时如果在浏览器中访问,则会提示证书失效,是否继续访问等等大家熟悉的场景。
对客户端代码做如下修改,目的就是不验证证书的有效性,即接受所有证书的认证。
新增如下方法:
private static bool AcceptAllCertifications(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certification, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors) { return true; }
base.SendAsync(request, cancellationToken)之前,调用下这个方法:
ServicePointManager.ServerCertificateValidationCallback += RemoteCertificateValidate;
即可。
或者不需要新增这个方法,直接在base.SendAsync(request, cancellationToken)之前新增一句:ServicePointManager.ServerCertificateValidationCallback += delegate { return true; };即可,简单粗暴,信任所有证书。
以上步骤完成之后,即可通过
var myResponse = myClient.GetAsync("https://192.168.1.166:7777/api/test/GetUser/id=123123&name=jiakai").Result;