public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Web API configuration and services config.Filters.Add(new ApiSecurityFilter()); config.Filters.Add(new ApiHandleErrorAttribute()); // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } }
8、添加写入日志类
public class ApiHandleErrorAttribute: ExceptionFilterAttribute { /// <summary> /// add by laiyunba /// </summary> /// <param>context oop</param> public override void OnException(HttpActionExecutedContext filterContext) { LoggerFactory.CreateLog().LogError(Messages.error_unmanagederror, filterContext.Exception); } }
9、利用微信小程序测试接口
var data = { UserName: username, Password: password, Action: 'Mobile', Sms: '' }; var timestamp = util.gettimestamp(); var nonce = util.getnonce(); if (username && password) { wx.request({ url: rootUrl + '/api/login', method: "POST", data: data, header: { 'content-type': 'application/json', 'timestamp': timestamp, 'nonce': nonce, 'signature': util.getMD5Staff(data, timestamp, nonce) }, success: function (res) { if (res.data) {
1)其中getMD5Staff函数:
function getMD5Staff(queryData, timestamp, nonce) { var staffId = getstaffId();//保存的key与webapi同步 var data = dictionaryOrderWithData(queryData); return md5.md5(timestamp + nonce + staffId + data); }
2)dictionaryOrderWithData函数:
function dictionaryOrderWithData(dic) { //eg {x:2,y:3,z:1} var result = ""; var sdic = Object.keys(dic).sort(function (a, b) { return a.localeCompare(b) }); var value = ""; for (var ki in sdic) { if (dic[sdic[ki]] == null) { value = "" } else { value = dic[sdic[ki]]; } result += sdic[ki] + value; } return result.replace(/\s/g, ""); }
10、测试日志
LaiyunbaApp Error: 2 : 2017-10-18 09:15:25 Unmanaged error in aplication, the exception information is Exception:System.Security.SecurityException: 安全性错误。 在 DistributedServices.MainBoundedContext.FilterAttribute.ApiSecurityFilter.OnActionExecuting(HttpActionContext actionContext) 在 System.Web.Http.Filters.ActionFilterAttribute.OnActionExecutingAsync(HttpActionContext actionContext, CancellationToken cancellationToken) --- 引发异常的上一位置中堆栈跟踪的末尾 --- 在 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) 在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) 在 System.Web.Http.Filters.ActionFilterAttribute.<ExecuteActionFilterAsyncCore>d__0.MoveNext() --- 引发异常的上一位置中堆栈跟踪的末尾 --- 在 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) 在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) 在 System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext() --- 引发异常的上一位置中堆栈跟踪的末尾 --- 在 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) 在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) 在 System.Web.Http.Controllers.ExceptionFilterResult.<ExecuteAsync>d__0.MoveNext() 失败的程序集的区域是: MyComputer LogicalOperationStack=2017-10-18 09:15:25 2017-10-18 09:15:25 DateTime=2017-10-18T01:15:25.1000017Z 2017-10-18 09:15:25 Callstack= 在 System.Environment.GetStackTrace(Exception e, Boolean needFileInfo) 在 System.Environment.get_StackTrace() 在 System.Diagnostics.TraceEventCache.get_Callstack() 在 System.Diagnostics.TraceListener.WriteFooter(TraceEventCache eventCache) 在 System.Diagnostics.TraceSource.TraceEvent(TraceEventType eventType, Int32 id, String message) 在 Infrastructure.Crosscutting.NetFramework.Logging.TraceSourceLog.TraceInternal(TraceEventType eventType, String message) 在 Infrastructure.Crosscutting.NetFramework.Logging.TraceSourceLog.LogError(String message, Exception exception, Object[] args) 在 System.Web.Http.Filters.ExceptionFilterAttribute.OnExceptionAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken) 在 System.Web.Http.Filters.ExceptionFilterAttribute.<ExecuteExceptionFilterAsyncCore>d__0.MoveNext() 在 System.Runtime.CompilerServices.AsyncTaskMethodBuilder.Start[TStateMachine](TStateMachine& stateMachine) 在 System.Web.Http.Filters.ExceptionFilterAttribute.ExecuteExceptionFilterAsyncCore(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken) 在 System.Web.Http.Filters.ExceptionFilterAttribute.System.Web.Http.Filters.IExceptionFilter.ExecuteExceptionFilterAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken) 在 System.Web.Http.Controllers.ExceptionFilterResult.<ExecuteAsync>d__0.MoveNext() 在 System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.Start[TStateMachine](TStateMachine& stateMachine) 在 System.Web.Http.Controllers.ExceptionFilterResult.ExecuteAsync(CancellationToken cancellationToken) 在 System.Web.Http.ApiController.ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancellationToken) 在 System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext() 在 System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1.Start[TStateMachine](TStateMachine& stateMachine) 在 System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) 在 System.Net.Http.HttpMessageInvoker.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) 在 System.Web.Http.Dispatcher.HttpRoutingDispatcher.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
至此,webapi加密工作已经全部完成,上述异常是直接访问url报的错误,必须在app环境下才可以正常访问。
总结:webapi加密机密很多,像微信小程序,用户很难拿到客户端app的源码,想知道我们的key也是无从说起。当然,我们也得定期更新app版本。