由于客户需要把原有HTTP后端服务升级为支持https的服务,因为原有的HTTP服务是一个基于WINDOWS服务内嵌HTTP监听服务实现的,并不支持https, 也不像其他IIS中部署的WebAPI服务那样直接加载HTTPS证书,所以这里需要修改原服务支持https和服务器环境上进行HTTPS端口绑定设置,具体如下:
(注:以下操作需要你已经具备了HTTPS证书。)
1、安装证书,双击pfx文件,安装到:“本地计算机”–>“个人”;
2、双击打开crt证书,详细信息中可以看到(certhash)指纹 相关信息;
3、执行端口绑定(默认443端口)
netsh http add sslcert ipport=0.0.0.0:8080 certhash=指纹 appid={程序GUID/newguid} clientcertnegotiation=enable
4、服务端程序实现:
using System;
public class HttpService
{public MyHttpServer(){System.Net.HttpListener httpListener = new System.Net.HttpListener();httpListener.AuthenticationSchemes = System.Net.AuthenticationSchemes.Anonymous;httpListener.Prefixes.Add("https://*:8000/"); // 支持httpshttpListener.Start();new System.Threading.Thread(new System.Threading.ThreadStart(delegate{while (true){try{System.Net.HttpListenerContext httpListenerContext = httpListener.GetContext();new System.Threading.Thread(new System.Threading.ParameterizedThreadStart((input) =>{System.Net.HttpListenerContext ctx = (System.Net.HttpListenerContext)input;System.Net.HttpListenerRequest request = ctx.Request;string pram = request.QueryString["Data"];//Get入参string responseMessage = string.Empty;//返回值if (!string.IsNullOrEmpty(pram)){//Get入参pramOrg = pram;pram = System.Web.HttpUtility.UrlDecode(pram);}//POST入参if (request.HttpMethod == "POST"){//处理业务请求StreamReader reader = new StreamReader(request.InputStream, Encoding.UTF8);pram = reader.ReadToEnd();reader.Close();reader.Dispose();}#region 业务处理try{//业务处理responseMessage = "业务结果";}catch (Exception ex){//异常处理responseMessage = ex.Message;}#endregion 业务处理#region 返回给调用者//输出类型httpListenerContext.Response.ContentType = "text/html; charset=UTF-8";//返回状态httpListenerContext.Response.StatusCode = 200;//设置授权,尝试解决Jquery跨域问题//httpListenerContext.Response.Headers["Access-Control-Allow-Origin"] = "*";//httpListenerContext.Response.Headers["Access-Control-Allow-Methods"] = "GET,POST";//httpListenerContext.Response.Headers["Access-Control-Max-Age"] = "1000";try{//输出界面内容if (!string.IsNullOrEmpty(responseMessage)){//返回文本内容using (StreamWriter writer = new StreamWriter(httpListenerContext.Response.OutputStream)){writer.Write(responseMessage);}}}catch{//刷新太快异常,不做处理}#endregion 返回给调用者})).Start(httpListenerContext);}catch{ }}})).Start();}
}
如上面执行端口绑定过程中报错,或添加失败,可以参考下面的处理:
1、检查netsh 命令的参数是否正确;
2、SSL 证书添加失败, 错误: 1312 指定的登录会话不存在。它可能已经被终止。的处理方法:
键盘 WIN+R 输入mmc.exe,如下:
点‘确定“,弹出如下控制台根节点界面,
选择 文件->添加/删除管理单元,或直接快捷键ctrl+m 弹出如下,并进行操作:
然后再到个人导入证书
最后将SSL证书绑定至端口号
netsh http add sslcert ipport=0.0.0.0:8080 certhash=指纹 appid={程序GUID/newguid} clientcertnegotiation=enable