1. 程式人生 > >.net core webapi使用nginx實現叢集和負載均衡

.net core webapi使用nginx實現叢集和負載均衡

第一步:先編寫webapi介面:

  

  介面介紹:

    1、介面採用appkey和appsecret

    2、訪問的話,在報文頭加上,appkey和sign。

      1、sign由請求地址(例如:http://www.xxx.com/api/user/xx/,那麼地址是/api/user/xx/)+appsecret+queryString或者報文體使用SHA1雜湊演算法得出。

  Filter程式碼:

 1 string appKey = "fjdsakljg";
 2         string appSecret = "dfhdjsklahfkdsbgkfdhtu
"; 3 4 public void OnAuthorization(AuthorizationFilterContext context) 5 { 6 string method = context.HttpContext.Request.Method.ToLower(); 7 string path = context.HttpContext.Request.Path.Value; 8 string thSign = ""; 9 StringValues appkeys;
10 StringValues signs; 11 if (!context.HttpContext.Request.Headers.TryGetValue("appKey", out appkeys)) 12 { 13 context.Result = new JsonResult(new APIResult<int> { Code = 1, Message = "appkey不存在" }); 14 return; 15 }
16 if (!context.HttpContext.Request.Headers.TryGetValue("sign", out signs)) 17 { 18 context.Result = new JsonResult(new APIResult<int> { Code = 1, Message = "sign不存在" }); 19 return; 20 } 21 string sign = signs.First(); 22 string key = appkeys.First(); 23 if (key != appKey) 24 { 25 context.Result = new JsonResult(new APIResult<int> { Code = 1, Message = "appkey錯誤" }); 26 return; 27 } 28 if (method == "get" || method == "delete") 29 { 30 IQueryCollection reqUrls = context.HttpContext.Request.Query; 31 StringBuilder sb = new StringBuilder(); 32 var querys = reqUrls.OrderBy(k => k.Key).Select(e => e.Key + "=" + e.Value); 33 string query = string.Join("&", querys); 34 thSign = CaclSHA(path + appSecret + query); 35 } 36 else 37 { 38 IQueryCollection reqUrls = context.HttpContext.Request.Query; 39 StringBuilder sb = new StringBuilder(); 40 var querys = reqUrls.OrderBy(k => k.Key).Select(e => e.Key + "=" + e.Value); 41 string query = string.Join("&", querys); 42 //讀取報文體 43 var requestBodyStream = new MemoryStream(); 44 context.HttpContext.Request.Body.CopyTo(requestBodyStream); 45 requestBodyStream.Seek(0, SeekOrigin.Begin); 46 string body = new StreamReader(requestBodyStream, Encoding.UTF8).ReadToEnd(); 47 requestBodyStream.Seek(0, SeekOrigin.Begin); 48 context.HttpContext.Request.Body = requestBodyStream; 49 thSign = CaclSHA(path+appSecret+body); 50 } 51 if (!sign.Equals(thSign,StringComparison.InvariantCultureIgnoreCase)) 52 { 53 context.Result = new JsonResult(new APIResult<int> { Code = 1, Message = "sign錯誤" }); 54 return; 55 } 56 }
View Code

2、編寫SDK包:

  

  

3、剩下就是部署了,我暫且拿虛擬機器來測試

  在ubuntu 16.04裝上nginx

  然後修改nginx的配置:

    

然後啟動。訪問就行了: