ServiceStack_AutoQuery

AutoQuery的作用
ServiceStack中的AutoQuery支持增加了类似于OData对Web Api的查询支持的自动查询功能。
AutoQuery在.Net Core中的配置

   public class AppHost : AppHostBase
    {
        //assembly 程序集的名称
        public AppHost()
            : base("TechStacks!", typeof(TechnologyServices).Assembly) { }
        //日志接口
        private static ILog log;

        // Configure your AppHost with the necessary configuration and dependencies your App needs
        //使用应用程序需要的必要配置和依赖项来配置AppHost
        public override void Configure(Container container)
        {
        // LogManager.LogFactory = new ConsoleLogFactory(debugEnabled:true);
            log = LogManager.GetLogger(typeof(AppHost));

            GetPlugin<NativeTypesFeature>().MetadataTypesConfig.BaseUrl = "https://www.techstacks.io";

            var debugMode = AppSettings.Get(nameof(HostConfig.DebugMode), false);
            //(设置配置)修改行为或删除未使用的插件
            SetConfig(new HostConfig {
                AddRedirectParamsToQueryString = true,
                DebugMode = debugMode,
            });

            JsConfig.Init(new ServiceStack.Text.Config {DateHandler = DateHandler.ISO8601});

            var dbFactory = new OrmLiteConnectionFactory(
                
                Environment.GetEnvironmentVariable("TECHSTACKS_DB") ??
                AppSettings.GetString("OrmLite.ConnectionString"),
                PostgreSqlDialect.Provider);
            
            dbFactory.RegisterDialectProvider(nameof(PostgreSqlDialect), PostgreSqlDialect.Provider);

            container.Register<IDbConnectionFactory>(dbFactory);

            //Plugins 插件
            // enable server-side rendering, see: https://sharpscript.net

            //auto-generating API ServiceStack Swagger support 
            Plugins.Add(new SharpPagesFeature());

            //Swagger UI 
            Plugins.Add(new AuthFeature(() => new CustomUserSession(), new IAuthProvider[] {
                new TwitterAuthProvider(AppSettings),
                new GithubAuthProvider(AppSettings),
                //Json web token 服务器的认证
                new JwtAuthProvider(AppSettings) {
                    RequireSecureConnection = false,
                    IncludeJwtInConvertSessionToTokenResponse = true,
                    CreatePayloadFilter = (payload, session) => {
                        var githubAuth = session.ProviderOAuthAccess.Safe()
                            .FirstOrDefault(x => x.Provider == "github");
                        payload["ats"] = githubAuth?.AccessTokenSecret;
                    },
                    PopulateSessionFilter = (session, obj, req) => {
                        session.ProviderOAuthAccess = new List<IAuthTokens> {
                            new AuthTokens {Provider = "github", AccessTokenSecret = obj["ats"]}
                        };
                    }
                },
                new DiscourseAuthProvider {
                    Provider = "servicestack",
                    DiscourseUrl = "https://forums.servicestack.net",
                },
            }) {
                HtmlRedirect = "/"
            });

            container.Register<IMarkdownProvider>(c =>
                new GitHubApiMarkdownProvider(Environment.GetEnvironmentVariable("GITHUB_AUTH")));

            container.Register<ITwitterUpdates>(new TwitterUpdates(
                AppSettings.GetString("WebStacks.ConsumerKey"),
                AppSettings.GetString("WebStacks.ConsumerSecret"),
                AppSettings.GetString("WebStacks.AccessToken"),
                AppSettings.GetString("WebStacks.AccessSecret")) {
                BaseUrl = AppSettings.GetString("PublicBaseUrl"),
            });
            // "username" "password" 受保护
            container.Register(new EmailProvider {
                //左边不为null,返回TECHSTACKS_SMTP_USER  否则返回smtp.UserName
                UserName = Environment.GetEnvironmentVariable("TECHSTACKS_SMTP_USER") ??
                           AppSettings.GetString("smtp.UserName"),
                Password = Environment.GetEnvironmentVariable("TECHSTACKS_SMTP_PASS") ??
                           AppSettings.GetString("smtp.Password"),
                EnableSsl = true,
                Host = AppSettings.GetString("smtp.Host"),
                Port = AppSettings.Get<int>("smtp.Port"),
                Bcc = AppSettings.GetString("smtp.Bcc"),
            });

            var authRepo = new OrmLiteAuthRepository<CustomUserAuth, UserAuthDetails>(dbFactory);
            container.Register<IUserAuthRepository>(authRepo);
            authRepo.InitSchema();
            using (var db = dbFactory.OpenDbConnection())
            {
                db.CreateTableIfNotExists<TechnologyStack>();
                db.CreateTableIfNotExists<Technology>();
                db.CreateTableIfNotExists<TechnologyChoice>();
                db.CreateTableIfNotExists<UserFavoriteTechnologyStack>();
                db.CreateTableIfNotExists<UserFavoriteTechnology>();

                var baseUrl = "https://techstacks.io";

                Plugins.Add(new SitemapFeature {
                    SitemapIndex = {
                        new Sitemap {
                            Location = baseUrl + "/sitemap-techstacks.xml",
                            AtPath = "/sitemap-techstacks.xml",
                            LastModified = DateTime.UtcNow,
                            
                            UrlSet = db.Select(db.From<TechnologyStack>().OrderByDescending(x => x.LastModified))
                                .Map(x => new SitemapUrl {
                                    Location = baseUrl + new ClientTechnologyStack {Slug = x.Slug}.ToAbsoluteUri(),
                                    LastModified = x.LastModified,
                                    ChangeFrequency = SitemapFrequency.Weekly,
                                }),
                        },
                        new Sitemap {
                            Location = baseUrl + "/sitemap-technologies.xml",
                            AtPath = "/sitemap-technologies.xml",
                            LastModified = DateTime.UtcNow,
                            UrlSet = db.Select(db.From<Technology>().OrderByDescending(x => x.LastModified))
                                .Map(x => new SitemapUrl {
                                    Location = baseUrl + new ClientTechnology {Slug = x.Slug}.ToAbsoluteUri(),
                                    LastModified = x.LastModified,
                                    ChangeFrequency = SitemapFrequency.Weekly,
                                })
                        },
                        new Sitemap {
                            Location = baseUrl + "/sitemap-users.xml",
                            AtPath = "/sitemap-users.xml",
                            LastModified = DateTime.UtcNow,
                            UrlSet = db.Select(db.From<CustomUserAuth>().OrderByDescending(x => x.ModifiedDate))
                                .Map(x => new SitemapUrl {
                                    Location = baseUrl + new ClientUser {UserName = x.UserName}.ToAbsoluteUri(),
                                    LastModified = x.ModifiedDate,
                                    ChangeFrequency = SitemapFrequency.Weekly,
                                })
                        },
                        new Sitemap {
                            Location = baseUrl + "/sitemap-organizations.xml",
                            AtPath = "/sitemap-organizations.xml",
                            LastModified = DateTime.UtcNow,
                            UrlSet = db.Select(db.From<Organization>().Where(x => x.Deleted == null)
                                    .OrderByDescending(x => x.Modified))
                                .Map(x => new SitemapUrl {
                                    Location = baseUrl + $"/{x.Slug}",
                                    LastModified = x.Modified,
                                    ChangeFrequency = SitemapFrequency.Weekly,
                                })
                        },
                        new Sitemap {
                            Location = baseUrl + "/sitemap-posts.xml",
                            AtPath = "/sitemap-posts.xml",
                            LastModified = DateTime.UtcNow,
                            UrlSet = db.Select(db.From<Post>()
                                    .Where(x => x.Type != PostType.Question && x.Deleted == null && x.Hidden == null)
                                    .Take(1000).OrderByDescending(x => x.Modified))
                                .Map(x => new SitemapUrl {
                                    Location = baseUrl + $"/posts/{x.Id}/{x.Slug}",
                                    LastModified = x.Modified,
                                    ChangeFrequency = SitemapFrequency.Hourly,
                                })
                        }
                    }
                });
            }

            //特定网站的访问CORS
            Plugins.Add(new CorsFeature(
                allowOriginWhitelist: new[] {
                    "https://techstacks.io", "https://www.techstacks.io",
                    "http://localhost:3000", "http://localhost:16325", "http://localhost:8080", "http://null.jsbin.com",
                    "http://run.plnkr.co"
                },
                allowCredentials: true,
                allowedHeaders: "Content-Type, Allow, Authorization",
                maxAge: 60 * 60)); //Cache OPTIONS permissions

            Plugins.Add(new ValidationFeature());
            container.RegisterValidators(typeof(AppHost).Assembly);
            container.RegisterValidators(typeof(TechnologyServices).Assembly);

            Plugins.Add(new AutoQueryMetadataFeature {
                AutoQueryViewerConfig = {
                    ServiceDescription = "Discover what technologies were used to create popular Websites and Apps",
                    ServiceIconUrl = "/img/app/logo-76.png",
                    BackgroundColor = "#0095F5",
                    TextColor = "#fff",
                    LinkColor = "#ffff8d",
                    BrandImageUrl = "/img/app/brand.png",
                    BrandUrl = "http://techstacks.io",
                    BackgroundImageUrl = "/img/app/bg.png",
                    IsPublic = true,
                    OnlyShowAnnotatedServices = true,
                }
            });
            Plugins.Add(new AutoQueryFeature {
                MaxLimit = 500,
                StripUpperInLike = false,
                ResponseFilters = {
                    ctx => ctx.Response.Meta["Cache"] = Stopwatch.GetTimestamp().ToString()
                }
            });
            Plugins.Add(new AdminFeature());
            Plugins.Add(new OpenApiFeature());

            RegisterTypedRequestFilter<IRegisterStats>((req, res, dto) =>
                dbFactory.RegisterPageView(dto.GetStatsId()));

            if (Config.DebugMode)
            {
                Plugins.Add(new LispReplTcpServer {
                    ScriptMethods = {
                        new DbScripts()
                    },
                    ScriptNamespaces = {
                        nameof(TechStacks),
                        $"{nameof(TechStacks)}.{nameof(ServiceInterface)}",
                        $"{nameof(TechStacks)}.{nameof(ServiceModel)}",
                    },
                });
            }

            container.Register<IMessageService>(c => new BackgroundMqService());
            var mqServer = container.Resolve<IMessageService>();

            mqServer.RegisterHandler<SendNotification>(ExecuteMessage, 4);
            mqServer.RegisterHandler<SendSystemEmail>(ExecuteMessage);
            mqServer.RegisterHandler<SendEmail>(ExecuteMessage);

            AfterInitCallbacks.Add(host => {
                mqServer.Start();
                ExecuteService(new RetryPendingNotifications());
            });
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值