ServiceStack_AutoQuery

不想你离开。 提交于 2020-02-07 08:51:43

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());
            });
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!