public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Web API 配置和服务 // 将 Web API 配置为仅使用不记名令牌身份验证。 config.SuppressDefaultHostAuthentication(); config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType)); // Web API 路由 config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); // 添加自定义消息处理 config.MessageHandlers.Add(new JoyMessageHandler()); } } WebApiConfig
编写单元测试:
[TestMethod()] public void GetTest() { var id = 10; var resultSuccess = $"\"value{id}\""; //不加密 Trace.WriteLine($"without encryption."); var url = $"api/ApiTest?id={id}"; Trace.WriteLine($"get url : {url}"); var response = http.GetAsync(url).Result; var result = response.Content.ReadAsStringAsync().Result; Assert.AreEqual(result, resultSuccess); Trace.WriteLine($"result : {result}"); //使用 方案1加密 Trace.WriteLine($"encryption case one."); url = $"api/ApiTest?code=" + $"id={id}".EncryptBase64().EncodeUrl(); Trace.WriteLine($"get url : {url}"); http.DefaultRequestHeaders.Clear(); http.DefaultRequestHeaders.Add("api_version", "1.0"); response = http.GetAsync(url).Result; result = response.Content.ReadAsStringAsync().Result; Trace.WriteLine($"result : {result}"); result = result.DecryptBase64(); Trace.WriteLine($"DecryptBase64 : {result}"); Assert.AreEqual(result, resultSuccess); //使用 方案2 加密通讯 Trace.WriteLine($"encryption case one."); url = $"api/ApiTest?code=" + $"id={id}".EncryptDES(MessageEncryptionVersion1_1.KEY).EncodeUrl(); Trace.WriteLine($"get url : {url}"); http.DefaultRequestHeaders.Clear(); http.DefaultRequestHeaders.Add("api_version", "1.1"); response = http.GetAsync(url).Result; result = response.Content.ReadAsStringAsync().Result; Trace.WriteLine($"result : {result}"); result = result.DecryptDES(MessageEncryptionVersion1_1.KEY); Trace.WriteLine($"DecryptBase64 : {result}"); Assert.AreEqual(result, resultSuccess); } ApiTestControllerTests
至此为止功能实现完毕..
四.思想延伸
要想更加安全的方案,可以将给每位用户生成不同的 private key , 利用AES加密解密
本Demo开源地址:
oschina
https://git.oschina.net/jonneydong/Webapi_Encryption
github