// 每次请求都会触发,一个页面会触发多次 protected override void RequestStartup(TinyIoCContainer container, Nancy.Bootstrapper.IPipelines pipelines, NancyContext context) { base.RequestStartup(container, pipelines, context); var formsAuthConfiguration = new FormsAuthenticationConfiguration() { RedirectUrl = "~/account/logon", UserMapper = container.Resolve <IUserMapper>(), }; FormsAuthentication.Enable(pipelines, formsAuthConfiguration); // Enabling sessions in Nancy CookieBasedSessions.Enable(pipelines); //放RequestStartup这里是每次请求时判断session,为了避免session过期,所以不放在ApplicationStartup pipelines.BeforeRequest += (ctx) => { var uid = ctx.Request.Session["TempUserId"]; var user = ctx.CurrentUser; if (user == null && uid == null) { ctx.Request.Session["TempUserId"] = "temp-" + Guid.NewGuid().ToString(); } return(null); }; }
protected override void ApplicationStartup(ILifetimeScope container, Nancy.Bootstrapper.IPipelines pipelines) { base.ApplicationStartup(container, pipelines); Conventions.StaticContentsConventions.Add(StaticContentConventionBuilder.AddDirectory("Images")); Conventions.StaticContentsConventions.Add(StaticContentConventionBuilder.AddDirectory("Scripts")); Conventions.StaticContentsConventions.Add(StaticContentConventionBuilder.AddDirectory("Content")); Conventions.StaticContentsConventions.Add(StaticContentConventionBuilder.AddDirectory("App")); }
// 每次请求都会触发,一个页面会触发多次 protected override void RequestStartup(TinyIoCContainer container, Nancy.Bootstrapper.IPipelines pipelines, NancyContext context) { base.RequestStartup(container, pipelines, context); // At request startup we modify the request pipelines to // include forms authentication - passing in our now request // scoped user name mapper. // // The pipelines passed in here are specific to this request, // so we can add/remove/update items in them as we please. var formsAuthConfiguration = new FormsAuthenticationConfiguration() { RedirectUrl = "~/account/logon", UserMapper = container.Resolve <IUserMapper>(), }; FormsAuthentication.Enable(pipelines, formsAuthConfiguration); //log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); //pipelines.OnError.AddItemToEndOfPipeline((ctx, exception) => { // Task tasks = new Task(() => { // log.Error(exception.Message); // }); // DefaultJsonSerializer serializer = new DefaultJsonSerializer(); // Response error = new JsonResponse(exception.Message, serializer); // error.StatusCode = HttpStatusCode.InternalServerError; // return error; //}); // Enabling sessions in Nancy CookieBasedSessions.Enable(pipelines); //放RequestStartup这里是每次请求时判断session,为了避免session过期,所以不放在ApplicationStartup pipelines.BeforeRequest += (ctx) => { var uid = ctx.Request.Session["TempUserId"]; var user = ctx.CurrentUser; if (user == null && uid == null) { //ctx.Request.Session["TempUserId"] = "temp-" + DateTime.Now.ToString("-yyyy-MM-dd-hh-mm-ss-fffff"); ctx.Request.Session["TempUserId"] = "temp-" + Guid.NewGuid().ToString(); } return(null); //return <null or a Response object>; }; }
protected override void ApplicationStartup(TinyIoCContainer container, Nancy.Bootstrapper.IPipelines pipelines) { base.ApplicationStartup(container, pipelines); this.Conventions.ViewLocationConventions.Insert(0, (viewName, model, context) => { return(string.Concat("Web/", viewName)); }); pipelines.AfterRequest.AddItemToEndOfPipeline(x => { x.Response.Headers.Add("Access-Control-Allow-Origin", "*"); x.Response.Headers.Add("Access-Control-Allow-Methods", "POST,GET,DELETE,PUT,OPTIONS"); x.Response.Headers.Add("Access-Control-Allow-Headers", "Accept, Origin, Content-type"); }); }
protected override void RequestStartup(TinyIoC.TinyIoCContainer container, Nancy.Bootstrapper.IPipelines pipelines, NancyContext context) { base.RequestStartup(container, pipelines, context); // At request startup we modify the request pipelines to // include forms authentication - passing in our now request // scoped user name mapper. // // The pipelines passed in here are specific to this request, // so we can add/remove/update items in them as we please. var formsAuthConfiguration = new FormsAuthenticationConfiguration() { RedirectUrl = "~/account/logon", UserMapper = container.Resolve <IUserMapper>(), }; FormsAuthentication.Enable(pipelines, formsAuthConfiguration); }
protected override void ApplicationStartup(TinyIoCContainer container, Nancy.Bootstrapper.IPipelines pipelines) { base.ApplicationStartup(container, pipelines); #if !DEBUG Cassette.Nancy.CassetteNancyStartup.OptimizeOutput = true; #endif DataAnnotationsValidator.RegisterAdapter(typeof(MatchAttribute), (v, d) => new CustomDataAdapter((MatchAttribute)v)); var docStore = container.Resolve <DocumentStore>("DocStore"); CleanUpDB(docStore); Raven.Client.Indexes.IndexCreation.CreateIndexes(typeof(Dinners_Index).Assembly, docStore); pipelines.OnError += (context, exception) => { Elmah.ErrorSignal.FromCurrentContext().Raise(exception); return(null); }; }
protected override void ApplicationStartup(TinyIoCContainer container, Nancy.Bootstrapper.IPipelines pipelines) { base.ApplicationStartup(container, pipelines); pipelines.EnableBasicAuthentication(new BasicAuthenticationConfiguration(container.Resolve <IUserValidator>(), "Projektname")); }
//protected override byte[] DefaultFavIcon //{ // get // { // if (favicon == null) // { // using (MemoryStream ms = new MemoryStream()) // { // Resource1.favicon.Save(ms); // favicon = ms.ToArray(); // } // } // return favicon; // } //} protected override void ApplicationStartup(TinyIoC.TinyIoCContainer container, Nancy.Bootstrapper.IPipelines pipelines) { base.ApplicationStartup(container, pipelines); DataAnnotationsValidator.RegisterAdapter(typeof(MatchAttribute), (v, d) => new CustomDataAdapter((MatchAttribute)v)); Func <TinyIoCContainer, NamedParameterOverloads, IDocumentSession> factory = (ioccontainer, namedparams) => { return(new RavenSessionProvider().GetSession()); }; container.Register <IDocumentSession>(factory); Raven.Client.Indexes.IndexCreation.CreateIndexes(typeof(IndexEventDate).Assembly, RavenSessionProvider.DocumentStore); Raven.Client.Indexes.IndexCreation.CreateIndexes(typeof(IndexUserLogin).Assembly, RavenSessionProvider.DocumentStore); Raven.Client.Indexes.IndexCreation.CreateIndexes(typeof(IndexMostPopularDinners).Assembly, RavenSessionProvider.DocumentStore); Raven.Client.Indexes.IndexCreation.CreateIndexes(typeof(IndexMyDinners).Assembly, RavenSessionProvider.DocumentStore); pipelines.OnError += (context, exception) => { Elmah.ErrorSignal.FromCurrentContext().Raise(exception); return(null); }; }
protected override void ApplicationStartup(Nancy.TinyIoc.TinyIoCContainer container, Nancy.Bootstrapper.IPipelines pipelines) { base.ApplicationStartup(container, pipelines); //Enable CSRF protection Nancy.Security.Csrf.Enable(pipelines); // Enabled cookie sessions Nancy.Session.CookieBasedSessions.Enable(pipelines); //Setup frame and origin options ( https://www.owasp.org/index.php/List_of_useful_HTTP_headers ) //may be overwritten by server (apache,ngix,iis,..) for config see https://developer.mozilla.org/en-US/docs/Web/HTTP/X-Frame-Options pipelines.AfterRequest.AddItemToEndOfPipeline((ctx) => { if (ctx.Response.StatusCode == HttpStatusCode.InternalServerError) { return; } ctx.Response.Headers.Add("X-Frame-Options", "SAMEORIGIN"); ctx.Response.Headers.Add("X-Download-Options", "noopen"); // IE extension ctx.Response.Headers.Add("X-Content-Type-Options", "nosniff"); ctx.Response.Headers.Add("X-XSS-Protection", "1; mode=block"); }); // Retain the casing in serialization of nancy json Nancy.Json.JsonSettings.RetainCasing = true; StaticConfiguration.CaseSensitive = false; // Enable debugging of nancy StaticConfiguration.EnableRequestTracing = false; // Dummy call to force the include of the Nancy.Serialization.JsonNet dll JsonNetSerializer a = new JsonNetSerializer(); a.CanSerialize("{}"); }
protected override void ApplicationStartup(Nancy.TinyIoc.TinyIoCContainer container, Nancy.Bootstrapper.IPipelines pipelines) { pipelines.AfterRequest += (ctx) => { ctx.Response.Headers.Add("Access-Control-Allow-Origin", "*"); }; }
/// <summary> /// Application Startup event /// </summary> /// <param name="container"></param> /// <param name="pipelines"></param> /// <param name="context"></param> protected override void RequestStartup(Nancy.TinyIoc.TinyIoCContainer container, Nancy.Bootstrapper.IPipelines pipelines, NancyContext context) { base.RequestStartup(container, pipelines, context); pipelines.BeforeRequest += (ctx) => { return(null); }; pipelines.AfterRequest += (ctx) => { }; //Handling Error here pipelines.OnError += (ctx, err) => { return(ctx.Response); }; }
protected override void ApplicationStartup(Nancy.TinyIoc.TinyIoCContainer container, Nancy.Bootstrapper.IPipelines pipelines) { // Cache the settings from the config file in memory SettingsRequest.RetrieveSettings(); // Cache the brandings from the config file in memory BrandingsRequest.RetrieveBrandings(); // Enable cookie based sessions CookieBasedSessions.Enable(pipelines); base.ApplicationStartup(container, pipelines); var authenticationConfiguration = new FormsAuthenticationConfiguration { RedirectUrl = "~/login", UserMapper = container.Resolve <IUserMapper>(), }; FormsAuthentication.Enable(pipelines, authenticationConfiguration); }
protected override void ApplicationStartup(Nancy.TinyIoc.TinyIoCContainer container, Nancy.Bootstrapper.IPipelines pipelines) { try { XDocument xDoc = XDocument.Load(HttpContext.Current.Server.MapPath("~/Config/settings.xml")); /* Load CloudPanel Settings */ var settings = from s in xDoc.Elements("Settings") select s; foreach (var s in settings) { Settings.HostingOU = s.Element("HostingOU").Value; Settings.PrimaryDC = s.Element("DomainController").Value; Settings.Username = s.Element("Username").Value; Settings.Password = s.Element("Password").Value; Settings.SuperAdmins = s.Element("SuperAdmins").Value; Settings.BillingAdmins = s.Element("BillingAdmins").Value; } /* Load Exchange Settings */ var exchange = from s in xDoc.Elements("Exchange") select s; foreach (var s in exchange) { Settings.ExchangeServer = s.Element("Server").Value; Settings.ExchangePFServer = s.Element("PFServer").Value; int defaultVersion = 2013; int.TryParse(s.Element("Version").Value, out defaultVersion); Settings.Version = defaultVersion; bool defaultBool = true; bool.TryParse(s.Element("SSL").Value, out defaultBool); Settings.ExchangeSSL = defaultBool; Settings.ExchangeConnection = s.Element("Connection").Value; } } catch (Exception ex) { log.Error(ex.ToString()); } CookieBasedSessions.Enable(pipelines); base.ApplicationStartup(container, pipelines); /*var authenticationConfiguration = * new FormsAuthenticationConfiguration * { * RedirectUrl = "~/login", * UserMapper = container.Resolve<IUserMapper>(), * }; * * FormsAuthentication.Enable(pipelines, authenticationConfiguration);*/ }
protected override void ApplicationStartup(TinyIoCContainer container, Nancy.Bootstrapper.IPipelines pipelines) { //Conventions.ViewLocationConventions.Add((viewName, model, context) => String.Concat("bin/views/", viewName)); }
protected override void ApplicationStartup(Nancy.TinyIoc.TinyIoCContainer container, Nancy.Bootstrapper.IPipelines pipelines) { Conventions.ViewLocationConventions.Add((viewName, model, context) => { return(string.Concat("scripts/views/", viewName)); }); Conventions.StaticContentsConventions.Add(StaticContentConventionBuilder.AddDirectory("assets", "scripts/assets")); StaticConfiguration.EnableRequestTracing = true; }
protected override void ApplicationStartup(Nancy.TinyIoc.TinyIoCContainer container, Nancy.Bootstrapper.IPipelines pipelines) { //CORS Enable pipelines.AfterRequest.AddItemToEndOfPipeline((ctx) => { ctx.Response.WithHeader("Access-Control-Allow-Origin", "*") .WithHeader("Access-Control-Allow-Methods", "POST,GET") .WithHeader("Access-Control-Allow-Headers", "Accept, Origin, Content-type"); }); base.ApplicationStartup(container, pipelines); }
protected override void ApplicationStartup(Nancy.TinyIoc.TinyIoCContainer container, Nancy.Bootstrapper.IPipelines pipelines) { string gzipflag = System.Configuration.ConfigurationManager.AppSettings["EnableGzip"] ?? "1"; if (gzipflag == "1") { AddGZip(pipelines); } pipelines.BeforeRequest += ctx => { bool valid = false; string msg = string.Empty; try { //LogUtil.WriteLog(ctx.Request.Url.ToString()); //放过登录入口 string url = ctx.Request.Path; IList <string> freePass = new List <string>();//免除通行证 freePass.Add("/Auth/"); freePass.Add("/Exhibition/"); freePass.Add("/SignBook/"); freePass.Add("/DialogMessages/"); freePass.Add("/Article/ArticleCommon"); for (int i = 0; i < freePass.Count; i++) { if (url.Contains(freePass[i])) { return(null); } } string appkey = ctx.Request.Headers["mars_appkey"].FirstOrDefault(); //LogUtil.WriteLog(appkey==null ? "NULL" : appkey); //LogUtil.WriteLog(AppServerDataInitializer.AppClients.Count > 0 ? AppServerDataInitializer.AppClients[appkey].AppKey : ""); if (appkey != null && AppServerDataInitializer.AppClients.ContainsKey(appkey)) { string token = ctx.Request.Headers["mars_token"].FirstOrDefault(); string sessionid = ctx.Request.Headers["mars_sid"].FirstOrDefault(); string tick = ctx.Request.Headers["mars_tick"].FirstOrDefault(); string version = ctx.Request.Headers["mars_version"].FirstOrDefault(); string method = ctx.Request.Method.ToLower(); if (!string.IsNullOrEmpty(token)) { SessionIdentity si = SessionCenter.GetIdentity(sessionid); if (si != null) { string data = method == "get" ? ctx.Request.Query.data : ctx.Request.Form.data; string token1 = GetSign(data, tick, appkey, sessionid, version, AppServerDataInitializer.AppClients[appkey].AppSecrect); StringBuilder sblog = new StringBuilder(); sblog.AppendFormat(",Path:{0}", ctx.Request.Url.Path); sblog.AppendFormat(",Method:{0}", method); sblog.AppendFormat(",Data:", data); sblog.AppendFormat(",Tick:{0}", tick); sblog.AppendFormat(",AppKey:{0}", appkey); sblog.AppendFormat(",SessionID:{0}", sessionid); sblog.AppendFormat(",Version:{0}", version); sblog.AppendFormat(",AppSecrect:{0}", AppServerDataInitializer.AppClients[appkey].AppSecrect); sblog.AppendFormat(",Token:{0}", token1); sblog.AppendFormat(",TokenFromClient:{0}", token); LogUtil.WriteLog(sblog.ToString()); if (token == token1) { si.Version = version; si.AppKey = appkey; MarsUserIdentity identity = new MarsUserIdentity(); identity.SessionID = si.SessionID; ctx.CurrentUser = identity; valid = true; } else { msg = "请求密钥错误!"; } } else { msg = "非法会话ID,请退出系统重新登录"; } } else { msg = "缺少会话密钥"; } } else { msg = "非法AppKey"; } } catch (Exception ex) { msg = ex.Message; LogUtil.WriteLog(ex); } if (!valid) { var res = new Response(); res.ContentType = "application/json; charset=utf-8"; res.Contents = s => { byte[] bs = Encoding.UTF8.GetBytes(JsonObj <JsonMessageBase> .ToJson(new JsonMessageBase() { Status = 0, Msg = msg })); s.Write(bs, 0, bs.Length); }; return(res); } return(null); }; base.ApplicationStartup(container, pipelines); }
protected override void RequestStartup(Nancy.TinyIoc.TinyIoCContainer container, Nancy.Bootstrapper.IPipelines pipelines, NancyContext context) { base.RequestStartup(container, pipelines, context); }
// The bootstrapper enables you to reconfigure the composition of the framework, // by overriding the various methods and properties. // For more information https://github.com/NancyFx/Nancy/wiki/Bootstrapper protected override void ApplicationStartup(TinyIoCContainer container, Nancy.Bootstrapper.IPipelines pipelines) { base.ApplicationStartup(container, pipelines); }
protected override void ApplicationStartup(Nancy.TinyIoc.TinyIoCContainer container, Nancy.Bootstrapper.IPipelines pipelines) { Wiring.Wire(); base.ApplicationStartup(container, pipelines); }