protected override void OnStart(string[] args) { try { //#if (DEBUG) // Debugger.Launch(); //#endif _server = WebApp.Start <Startup>(url: _WEB_API_SERVER_ADD); AutoNLog.Log4Info("成功启动WebApiServer"); } catch (Exception ex) { AutoNLog.Log4Exception("启动WebApiServer失败,", ex); } }
protected override void OnStop() { try { if (_server != null) { _server.Dispose(); } base.OnStop(); AutoNLog.Log4Info("成功停止WebApiServer"); } catch (Exception ex) { AutoNLog.Log4Exception("停止WebApiServer失败,", ex); } }
protected virtual HttpResponseMessage RespExMsg(Exception ex) { MyLog log = new MyLog(WebApiGlobal._MyLogPath); log.log(ex.Message); AutoNLog.Log4Exception(CustomErrorMessage.发生异常.ToString(), ex); CustomHttpResponseMessage r = new CustomHttpResponseMessage(); r.RespData = ""; r.ErrorMessage = CustomErrorMessage.操作失败.ToString(); r.RespStatus = CustomHttpResponseMessageStatus.Error.ToString(); return(new HttpResponseMessage { Content = new StringContent(JsonConvert.SerializeObject(r, _JsonSetting), Encoding.GetEncoding("UTF-8"), "application/json") }); }
//REF: http://blog.kkbruce.net/2012/05/aspnet-web-api-8-http-http-message.html //REF: http://bit.ly/16lpGKM protected override System.Threading.Tasks.Task <HttpResponseMessage> SendAsync( HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { try { return(base.SendAsync(request, cancellationToken).ContinueWith((task) => { HttpResponseMessage resp = task.Result as HttpResponseMessage; resp.Headers.Remove("Server"); resp.Headers.Remove("X-Powered-By"); AutoNLog.Log4Trace(request, resp); return resp; })); } catch (Exception ex) { AutoNLog.Log4Exception(CustomErrorMessage.Trace发生异常.ToString(), ex); throw ex; } }
static void Main(string[] args) { try { //System.Windows.Forms.Application.Run(new Form1()); AutoNLog.Log4Info("开始"); using (WebApp.Start <Startup>(url: _WEB_API_SERVER_ADD)) { //HttpClient client = new HttpClient(); //HttpResponseMessage response = client.GetAsync("http://localhost:9527/api/Help/GetCarSize").Result; //response.Headers.Remove("Server"); //Console.WriteLine(response); //Console.WriteLine(response.Content.ReadAsStringAsync().Result); AutoNLog.Log4Info("成功"); Console.ReadLine(); } } catch (Exception ex) { AutoNLog.Log4Exception("WebApiSelfHost发生异常:", ex); } }
//protected virtual bool IsSysKey() //{ // try // { // string UserKey = this.Request.Headers.GetValues(WebApiGlobal._USERKEY).ToArray()[0]; // //string requestUri = this.Request.RequestUri.OriginalString; // string requestUri = this.Request.Headers.GetValues(WebApiGlobal._ORI_REQUEST_URL).ToArray()[0]; // //string requestUri = this.Request.RequestUri.OriginalString; // requestUri = System.Web.HttpUtility.UrlDecode(requestUri); // DataTable dt = RAMCache.Instance.UserKeyAndSalt; // DataRow[] dr = dt.Select(WebApiGlobal._USERKEY + " = '" + UserKey + "'"); // if (dr.Length == 1) // { // string keyDataBase = dr[0][WebApiGlobal._DATABASENAME].ToString(); // string userCode = dr[0][WebApiGlobal._USERCODE].ToString(); // if (keyDataBase == ChooseDataBase.System.ToString()) // { // return true; // } // else // { // AutoNLog.Log4Warn(CustomErrorMessage.UserKey跨库使用.ToString() + ",UserCode:" + userCode + ",RequestUri:" + requestUri); // return false; // } // } // else // { // AutoNLog.Log4Warn(CustomErrorMessage.UserKey无效.ToString() + ",UserKey:" + UserKey + ",RequestUri:" + requestUri); // return false; // } // } // catch (Exception ex) // { // AutoNLog.Log4Exception(CustomErrorMessage.发生异常.ToString(), ex); // return false; // } //} //protected virtual bool VerifyUserKey(Params4ApiCRUD P) //{ // string UserKey = this.Request.Headers.GetValues(WebApiGlobal._USERKEY).ToArray()[0]; // //string SHA512UserKey = Encryption.Instance.StringToSHA512Hash(UserKey); // DataTable dt = RAMCache.Instance.UserKeyAndSalt; // DataRow[] dr = dt.Select(WebApiGlobal._USERKEY + " = '" + UserKey + "'"); // string chooseDataBase = DataBaseConnFactory.Instance.GetUserKeyAndDataBase(P.chooseDataBase); // string keyDataBase = dr[0][WebApiGlobal._DATABASENAME].ToString(); // string userCode = dr[0][WebApiGlobal._USERCODE].ToString(); // if (chooseDataBase == keyDataBase) // { // P.UserCode = userCode; // return true; // } // else // { // string ClientTS = this.Request.Headers.GetValues(WebApiGlobal._TIMESPAN).ToArray()[0]; // //string requestUri = this.Request.RequestUri.AbsoluteUri; // string requestUri = this.Request.RequestUri.OriginalString; // requestUri = System.Web.HttpUtility.UrlDecode(requestUri); // string str4Log = "ChooseDataBase:" + chooseDataBase + ",UserCode:" + userCode + ",ClientTS:" + ClientTS + ",requestUri:" + requestUri; // AutoNLog.Log4Warn(CustomErrorMessage.UserKey跨库使用.ToString() + str4Log); // return false; // } //} protected virtual bool VerifyUserKey(Params4ApiCRUD P, decimal timespan = 600)//默认允许时差十分钟 { try { bool iscorrect = false; string ClientTS = this.Request.Headers.GetValues(WebApiGlobal._TIMESPAN).ToArray()[0]; string ServerTS = CommonMethod.UTCTS; //string requestUri = this.Request.RequestUri.AbsoluteUri; string requestUri = this.Request.Headers.GetValues(WebApiGlobal._ORI_REQUEST_URL).ToArray()[0]; //string requestUri = this.Request.RequestUri.OriginalString; requestUri = System.Web.HttpUtility.UrlDecode(requestUri); string UserKey = this.Request.Headers.GetValues(WebApiGlobal._USERKEY).ToArray()[0]; string chooseDataBase = P.chooseDataBase.ToString(); DataTable dt = RAMCache.Instance.UserKeyAndSalt; DataRow[] dr = dt.Select(WebApiGlobal._USERKEY + " = '" + UserKey + "'"); string str4ErrLog = ""; if (dr.Length == 1) { string UserCode = dr[0][WebApiGlobal._USERCODE].ToString(); string UserSalt = dr[0][WebApiGlobal._USERSALT].ToString(); string OriKey = dr[0][WebApiGlobal._DECODE_USERKEY].ToString(); string KeyDataBase = dr[0][WebApiGlobal._DATABASENAME].ToString(); str4ErrLog = "UserCode:" + UserCode + ",ClientTS:" + ClientTS + ",requestUri:" + requestUri; decimal tsc = ClientTS.ToDecimalEx(0); decimal tss = ServerTS.ToDecimalEx(0); decimal diff = tss - tsc; if (diff > timespan || diff < -5) { AutoNLog.Log4Warn(CustomErrorMessage.TimeSpan错误.ToString() + str4ErrLog); return(iscorrect); } if (chooseDataBase != KeyDataBase) { AutoNLog.Log4Warn(CustomErrorMessage.UserKey跨库使用.ToString() + "ChooseDataBase:" + chooseDataBase + str4ErrLog); return(iscorrect); } string ClientSHA256Sign = this.Request.Headers.GetValues(WebApiGlobal._SHA256).ToArray()[0]; string ServerSHA256Sign = CommonMethod.StringToSHA256Hash(OriKey + requestUri + ClientTS + UserSalt); if (ClientSHA256Sign != ServerSHA256Sign) { AutoNLog.Log4Warn(CustomErrorMessage.Hash校验错误.ToString() + str4ErrLog + ",ClientSHA256Sign:" + ClientSHA256Sign + ",ServerSHA256Sign:" + ServerSHA256Sign); return(iscorrect); } P.UserCode = UserCode; iscorrect = true; return(iscorrect); } else { AutoNLog.Log4Warn(CustomErrorMessage.UserKey无效.ToString() + UserKey); return(iscorrect); } } catch (Exception ex) { AutoNLog.Log4Exception(CustomErrorMessage.Hash校验异常.ToString(), ex); return(false); } }
// http://stackoverflow.com/a/17227764/19020 // http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2 public static void Ini(IAppBuilder appBuilder) { //DateTime dt = DateTime.Parse("2017-01-02"); //try //{ // DateTime dt = GetNetTime.GetStandardTime(); // SetNetTime.SetTime(GetNetTime.GetStandardTime()); //} //catch (Exception ex) //{ // AutoNLog.Log4Info("同步时间失败" + ex); //} //string authKey = System.Configuration.ConfigurationManager.ConnectionStrings[WebApiGlobal._AUTHKEY].ConnectionString; try { //DateTime dt = GetNetTime.GetStandardTime(); //SetNetTime.SetTime(dt); MyLicense lic = ReadFromLic.ReadLic(AuthKeys._AuthFileKEY, AuthKeys._AuthFilePath); if (lic == null) { throw new Exception("未解密Lic"); } string CpuID = GetComputerInfo.GetCpuID(); string HDid = GetComputerInfo.GetHDid(); string ComputerInfo = CpuID + HDid + lic.PeriodDate.ToStringEx() + "4x}ty#N3*w[2bXK2ne(DRLKov%NhmJ#Z"; RSAAuth _RSA = new RSAAuth(); string _PublicKey = _RSA.ReadPublicKey(AuthKeys._PublicKeyPath); string Hash1 = _RSA.GetSHA512Hash(ComputerInfo); string Hash4Validate = _RSA.GetSHA512Hash(Hash1); if (_RSA.SignatureDeformatter(_PublicKey, Hash4Validate, lic.SignValue.ToStringEx())) { if (DateTime.Parse(lic.PeriodDate) < DateTime.Now) { throw new Exception("已过期,PeriodDate:" + lic.PeriodDate.ToStringEx() + "SignValue:" + lic.SignValue.ToStringEx()); } } else { throw new Exception("非法使用,PeriodDate:" + lic.PeriodDate.ToStringEx() + "SignValue:" + lic.SignValue.ToStringEx()); } } catch (Exception ex) { AutoNLog.Log4Info("检验错误" + ex.Message.ToStringEx() + ex); throw ex; } Type RAMCacheController = typeof(WebApi.Controller.RAMCacheController); Type web_Api_HelperController = typeof(WebApi.Controller.web_Api_HelperController); Type tb_TMS_DDController = typeof(WebApi.Controller.TMS_DDController); HttpConfiguration config = new HttpConfiguration(); config.Formatters.JsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented; config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; config.Formatters.JsonFormatter.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm"; config.Formatters.JsonFormatter.SerializerSettings.NullValueHandling = NullValueHandling.Ignore; appBuilder.Use((context, next) => { context.Response.Headers.Remove("Server"); return(next.Invoke()); }); appBuilder.UseStageMarker(PipelineStage.PostAcquireState); // // List of delegating handlers. // DelegatingHandler[] handlers = new DelegatingHandler[] { // new MessageHandler3() // }; // // Create a message handler chain with an end-point. // var routeHandlers = HttpClientFactory.CreatePipeline( // new HttpControllerDispatcher(config), handlers); // Web API 配置和服务 // 将 Web API 配置为仅使用不记名令牌身份验证。 config.SuppressDefaultHostAuthentication(); //config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType)); //config.MapHttpAttributeRoutes(); //可将路由放到基类中 config.MapHttpAttributeRoutes(new CustomDirectRouteProvider()); //没有action,则两个方法都是Get开头会报错,改为api/{controller}/{action}/{id} config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } //constraints: null, //handler: new MessageHandler1() //handler: routeHandlers ); config.Filters.Add(new MyActionFilterAttribute()); config.Filters.Add(new MyExceptionHandlingAttribute()); //var traceWriter = new SystemDiagnosticsTraceWriter() //{ // IsVerbose = true //}; ////config.Services.Replace(typeof(ITraceWriter), traceWriter); //config.EnableSystemDiagnosticsTracing(); //config.MessageHandlers.Add(new ThrottlingHandler() //{ // Policy = new ThrottlePolicy(perSecond: 1, perMinute: 30) // { // //Ip限流,访问api/values后,所有后续访问api/values/xxx的请求都会被拒绝掉 // IpThrottling = true, // //IpWhitelist = new List<string> { "::1", "192.168.0.0/24" }, // IpRules = new Dictionary<string, RateLimits> // { // { "192.168.1.1", new RateLimits { PerSecond = 2 } }, // { "192.168.2.0/24", new RateLimits { PerMinute = 30, PerHour = 30*60, PerDay = 30*60*24 } } // }, // //如果同一个ip,在同一秒内,调用了2次api/values,其最后一次的调用将会被拒绝掉。 // //如果想接口通过唯一key去识别限制客户端,忽略客户端的ip地址限制,应该配置IpThrottling为false。 // ClientThrottling = true, // ClientWhitelist = new List<string> { "admin-key" }, // ClientRules = new Dictionary<string, RateLimits> // { // { "api-client-key-1", new RateLimits { PerMinute = 40, PerHour = 400 } }, // { "api-client-key-9", new RateLimits { PerDay = 2000 } } // }, // EndpointRules = new Dictionary<string, RateLimits> // { // { "api/RAM/Mgr/RefreshUserKey", new RateLimits { PerSecond = 2, PerMinute = 100, PerHour = 1000 } } // }, // //拒绝累加技术 // StackBlockedRequests = true, // //Ip端点限流,同一秒内你也访问api/values/1了,请求将不会被拒绝,因为它们走的是不同的路由。 // EndpointThrottling = true // }, // //如果是owin寄宿,替换成PolicyMemoryCacheRepository // //PolicyRepository= new PolicyMemoryCacheRepository(), // //policyRepository: new PolicyCacheRepository(), // //自寄宿在Owin上的WebApi用MemoryCacheRepository // Repository = new MemoryCacheRepository(), // Logger= new TracingThrottleLogger(traceWriter) // //Repository = new CacheRepository()//CacheRepository使用的是Asp.net版本的缓存。 //} //); ////config.MessageHandlers.Add(new CustomHeaderHandler()); ////config.MessageHandlers.Add(new MessageHandler1()); ////config.MessageHandlers.Add(new RemoveHttpHeadersModule()); appBuilder.UseWebApi(config); //config.Formatters.Remove(config.Formatters.XmlFormatter); config.MessageHandlers.Add(new NLogHandler()); //config.MapHttpAttributeRoutes(new CustomDirectRouteProvider()); //HelpPageConfig.Register(config); //SwaggerNet.PreStart(); var jsonFormatter = new JsonMediaTypeFormatter(); //optional: set serializer settings here config.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter)); //AutoNLog.Log4Info("正在启动WebApiServer"); }