public static IServiceCollection AddCustomSwagger( this IServiceCollection services, IApiInfo apiInfo ) => services .AddSwaggerGen(options => { options.DescribeAllEnumsAsStrings(); options.SwaggerDoc(apiInfo.Version, new Info { Title = apiInfo.Title, Version = apiInfo.Version, Description = apiInfo.Version }); if (apiInfo.AuthenticationAuthority != null) { options.AddSecurityDefinition("oauth2", new OAuth2Scheme { Type = "oauth2", Flow = "implicit", AuthorizationUrl = $"{apiInfo.AuthenticationAuthority}/connect/authorize", TokenUrl = $"{apiInfo.AuthenticationAuthority}/connect/token", Scopes = apiInfo.Scopes }); } options.DocumentFilter <LowerCaseDocumentFilter>(); options.OperationFilter <AuthorizeCheckOperationFilter>(apiInfo); options.OperationFilter <DescriptionOperationFilter>(); });
/// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IApiInfo apiInfo) { //NLog.LogManager.LoadConfiguration("NLog.config"); app.UseForwardedHeaders(new ForwardedHeadersOptions { ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto }); app.UseDeveloperExceptionPage(); app.UsePermissiveCors(); app.UseCustomSwagger(apiInfo); app.UseRouting(); //app.UseAuthentication(); //app.UseMvc(); app.UseStaticFiles(); app.UseConsulRegisterService(Configuration); app.UseEndpoints(endpoints => { app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); }); }
public static IApplicationBuilder UseMagicOnionWebHost(this IApplicationBuilder app, IApiInfo apiInfo, Assembly[] searchAssemblies = null) { var applicationLifetime = app.ApplicationServices.GetRequiredService <IApplicationLifetime>() ?? throw new ArchitectureException($"Missing Dependency: {nameof(IApplicationLifetime)}"); var loggerFactory = app.ApplicationServices.GetRequiredService <ILoggerFactory>(); var logger = loggerFactory.CreateLogger(apiInfo.ApiName); GrpcEnvironment.SetLogger(new GrpcLogger(logger)); var grpcServer = InitializeGrpcServer(apiInfo, searchAssemblies); applicationLifetime.ApplicationStopping.Register(() => { try { grpcServer.ShutdownAsync().Wait(); } catch (Exception ex) { logger.LogError(ex, $"GrpcServer had shutdown"); } logger.LogInformation("GrpcServer had shutdown"); }); return(app); }
/// <summary> /// Initializing the GRPC service /// </summary> private static GRpcServer InitializeGrpcServer(IApiInfo apiInfo, Assembly[] searchAssemblies) { var option = new MagicOnionOptions { #if DEBUG IsReturnExceptionStackTraceInErrorDetail = true #else IsReturnExceptionStackTraceInErrorDetail = false #endif }; if (searchAssemblies == null) { searchAssemblies = new[] { Assembly.GetEntryAssembly(), }; } var grpcServer = new GRpcServer { Ports = { new ServerPort(apiInfo.BindAddress, apiInfo.BindPort, ServerCredentials.Insecure) }, Services = { MagicOnionEngine.BuildServerServiceDefinition( searchAssemblies, option) } }; grpcServer.Start(); return(grpcServer); } }
private IFlurlRequest BuildGetRequest(IApiInfo apiInfo, string apiMethod, object queryParams, ISynologySession session = null) { var flurlRequest = _flurlClient .Request(apiInfo.Path) .SetQueryParams(new { api = apiInfo.Name, version = apiInfo.Version, method = apiMethod, }); flurlRequest.SetQueryParams(queryParams); if (!string.IsNullOrWhiteSpace(apiInfo.SessionName)) { flurlRequest.SetQueryParam("session", apiInfo.SessionName); } if (session != null) { flurlRequest.SetQueryParam("_sid", session.Sid); } return(flurlRequest); }
public static IMvcBuilder AddCustomWebApi(this IServiceCollection services, IApiInfo apiInfo) { return(services.AddWebApi(options => { options.OutputFormatters.Remove(new XmlDataContractSerializerOutputFormatter()); options.UseCentralRoutePrefix(new RouteAttribute($"api/{apiInfo.Version}/{apiInfo.RoutePrefix}/[controller]")); })); }
public SynologyApiException(IApiInfo apiInfo, string apiMethod, int errorCode, string errorDescription = "") : this($"The Synology API Request failed.\n" + $"Error Code: \"{errorCode}\"\n" + $"Error Description: \"{errorDescription}\"\n" + $"API: \"{apiInfo.Name}\" \n" + $"Method: \"{apiMethod}\" \n" + $"Version: \"{apiInfo.Version}\"", apiInfo, apiMethod, errorCode, errorDescription) { }
public void Configure( IApplicationBuilder app, IHostingEnvironment env, IApiInfo apiInfo) => app .UseDeveloperExceptionPage() .UseApplication() .UsePermissiveCors() .UseCustomSwagger(apiInfo) .UseAuthentication() .UseMvcWithDefaultRoute();
public FileStationUploadEndpoint(ISynologyHttpClient synologyHttpClient, IApiInfo apiInfo, ISynologySession session, IFileSystem fileSystem) { _synologyHttpClient = synologyHttpClient; _apiInfo = apiInfo; _session = session; _fileSystem = fileSystem; }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApiInfo apiInfo) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseMvc() .UseCustomSwagger(apiInfo); //启用swagger //app.UseSwaggerEx(); }
public AuthApiTests(SynologyFixture synologyFixture) { _fixture = new Fixture(); _httpTest = new HttpTest(); _synologyFixture = synologyFixture; _apiInfo = _synologyFixture.ApisInfo.FileStationUploadApi; _authApi = new AuthApi( synologyFixture.SynologyHttpClient, _apiInfo); }
public async Task <T> GetAsync <T>( IApiInfo apiInfo, string apiMethod, object queryParams, ISynologySession session = null) { var flurlRequest = BuildGetRequest(apiInfo, apiMethod, queryParams, session); using (var httpResponse = await flurlRequest.GetAsync()) { return(await HandleSynologyResponse <T>(httpResponse, apiInfo, apiMethod)); } }
public ReadOnlyPagedCollection(IApiResponse <IList <T> > response, Func <Uri, Task <IApiResponse <IList <T> > > > nextPageFunc) : base(response != null ? response.Body ?? new List <T>() : new List <T>()) { response.ArgumentNotNull(nameof(response)); nextPageFunc.ArgumentNotNull(nameof(nextPageFunc)); this.nextPageFunc = nextPageFunc; if (response != null) { info = response.HttpResponse.ApiInfo; } }
/// <summary> /// Initializing the GRPC service /// </summary> /// <param name="config">Grpc setting</param> private static GRpcServer InitializeGrpcServer(IApiInfo apiInfo) { var grpcServer = new GRpcServer { Ports = { new ServerPort(apiInfo.BindAddress, apiInfo.BindPort, ServerCredentials.Insecure) }, Services = { MagicOnionEngine.BuildServerServiceDefinition() } }; grpcServer.Start(); return(grpcServer); }
public SynologyApiException( string message, IApiInfo apiInfo, string apiMethod, int errorCode, string errorDescription, Exception innerException = null) : base(message, innerException) { ApiInfo = apiInfo; ApiMethod = apiMethod; ErrorCode = errorCode; ErrorDescription = errorDescription; }
public async Task <T> PostAsync <T>(IApiInfo apiInfo, string apiMethod, HttpContent content, ISynologySession session = null) { var flurlRequest = _flurlClient.Request(apiInfo.Path); if (session != null) { flurlRequest.SetQueryParam("_sid", session.Sid); } using (var httpResponse = await flurlRequest.PostAsync(content)) { return(await HandleSynologyResponse <T>(httpResponse, apiInfo, apiMethod)); } }
private async Task <IResponse> RunRequest(IRequest request, CancellationToken cancellationToken) { request.Headers.Add("User-Agent", UserAgent); await authenticator.Apply(request).ConfigureAwait(false); var response = await httpClient.Send(request, cancellationToken).ConfigureAwait(false); if (response != null) { latestApiInfo = response.ApiInfo.Clone(); } HandleErrors(response); return(response); }
public static IServiceCollection AddCustomSwagger( this IServiceCollection services, IApiInfo apiInfo ) => services .AddSwaggerGen(options => { //TODO: //options.DescribeAllEnumsAsStrings(); options.SwaggerDoc(apiInfo.Version, new OpenApiInfo { Title = apiInfo.Title, Version = apiInfo.Version, Description = apiInfo.Version }); if (apiInfo.AuthenticationAuthority != null) { options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme { Description = "请输入OAuth接口返回的Token,前置Bearer。示例:Bearer {Token}", Name = "Authorization", In = ParameterLocation.Header,//jwt默认存放Authorization信息的位置(请求头中) Type = SecuritySchemeType.ApiKey, OpenIdConnectUrl = new Uri(apiInfo.AuthenticationAuthority) }); options.AddSecurityRequirement(new OpenApiSecurityRequirement { //{ //new OpenApiSecurityScheme //{ // Reference = new OpenApiReference() // { // Id = "Bearer", // Type = ReferenceType.SecurityScheme, // } //}, Array.Empty<string>() //} }); } options.DocumentFilter <LowerCaseDocumentFilter>(); options.OperationFilter <AuthorizeCheckOperationFilter>(apiInfo); //options.OperationFilter<DescriptionOperationFilter>(); });
public FileStationApiUploadEndpointTests(SynologyFixture synologyFixture) { _fixture = new Fixture(); _httpTest = new HttpTest(); _synologyFixture = synologyFixture; _apiInfo = _synologyFixture.ApisInfo.FileStationUploadApi; var fileSystem = new MockFileSystem(new Dictionary <string, MockFileData> { { TestFilePath, new MockFileData("Test file") } }); _fileStationUploadEndpoint = new FileStationUploadEndpoint( synologyFixture.SynologyHttpClient, _apiInfo, new SynologySession(_fixture.Create <string>()), fileSystem); }
/// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime applicationLifetime, IApiInfo apiInfo) { loggerFactory.AddNLog(); NLog.LogManager.LoadConfiguration("NLog.config"); app.UseForwardedHeaders(new ForwardedHeadersOptions { ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto }); app.UseDeveloperExceptionPage() .UsePermissiveCors() .UseCustomSwagger(apiInfo) .UseAuthentication() .UseMvc() .UseStaticFiles() .UseConsulRegisterService(Configuration); }
public static IApplicationBuilder UseCustomSwagger( this IApplicationBuilder app, IApiInfo apiInfo ) => app .UseSwagger() .UseSwaggerUI(c => { c.SwaggerEndpoint($"/swagger/{apiInfo.Version}/swagger.json", $"{apiInfo.Title} {apiInfo.Version}"); if (apiInfo.AuthenticationAuthority != null) { c.ConfigureOAuth2( apiInfo.SwaggerAuthInfo.ClientId, apiInfo.SwaggerAuthInfo.Secret, apiInfo.SwaggerAuthInfo.Realm, $"{apiInfo.Title} - ${apiInfo.Version} - Swagger UI" ); } });
public static IHostBuilder UseMagicOnionHost(this IHostBuilder builder, IApiInfo apiInfo, Assembly[] searchAssemblies = null, MagicOnionOptions options = null, IEnumerable <ChannelOption> channelOptions = null) { if (searchAssemblies == null) { searchAssemblies = new[] { Assembly.GetEntryAssembly() }; } return(MagicOnion.Hosting.MagicOnionServerServiceExtension.UseMagicOnion(builder, new[] { new ServerPort(apiInfo.BindAddress, apiInfo.BindPort, ServerCredentials.Insecure) }, options ?? new MagicOnionOptions(), null, searchAssemblies, channelOptions)); }
public static IServiceCollection AddCustomIdentity( this IServiceCollection services, IApiInfo apiInfo ) { JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme) .AddIdentityServerAuthentication(options => { options.Authority = apiInfo.AuthenticationAuthority; options.RequireHttpsMetadata = false; options.ApiName = apiInfo.ApiName; options.ApiSecret = apiInfo.ApiSecret; }); services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>(); services.AddScoped <IUser, HttpContextUser>(); return(services); }
public static IApplicationBuilder UseCustomSwagger( this IApplicationBuilder app, IApiInfo apiInfo ) => app.UseSwagger(c => { //c.PreSerializeFilters.Add((swagger, httpReq) => swagger.Host = httpReq.Host.Value); }) .UseSwaggerUI(c => { c.SwaggerEndpoint($"/swagger/{apiInfo.Version}/swagger.json", $"{apiInfo.Title} {apiInfo.Version}"); if (apiInfo.AuthenticationAuthority != null) { //c.ConfigureOAuth2( // apiInfo.SwaggerAuthInfo.ClientId, // apiInfo.SwaggerAuthInfo.Secret, // apiInfo.SwaggerAuthInfo.Realm, // $"{apiInfo.Title} - ${apiInfo.Version} - Swagger UI" //); } });
public static HttpClient Build(IApiInfo apIInfo) { HttpClientHandler handler = new HttpClientHandler() { SslProtocols = SslProtocols.Tls12 }; handler.ServerCertificateCustomValidationCallback += (request, cert, chain, errors) => { return(true); }; HttpClient httpClient = new HttpClient(handler); httpClient.BaseAddress = apIInfo.BaseAddress; httpClient.DefaultRequestHeaders.Accept.Clear(); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); return(httpClient); }
private static IApplicationBuilder UseCustomSwaggerUi(this IApplicationBuilder app, IApiInfo apiInfo) { return(app.UseSwaggerUI(c => { c.SwaggerEndpoint($"/swagger/{apiInfo.Version}/swagger.json", $"{apiInfo.Title} {apiInfo.Version}"); })); }
public static IApplicationBuilder UseCustomSwagger(this IApplicationBuilder app, IApiInfo apiInfo) { return(app.UseSwagger().UseCustomSwaggerUi(apiInfo)); }
public static IServiceCollection AddCustomSwagger(this IServiceCollection services, IApiInfo apiInfo) { return(services .AddSwaggerGen(options => { options.DescribeAllEnumsAsStrings(); options.SwaggerDoc(apiInfo.Version, new Info { Title = apiInfo.Title, Version = apiInfo.Version, Description = $"{apiInfo.Title} {apiInfo.Version?.ToUpper()}" }); options.AddSecurityDefinition("Bearer", new ApiKeyScheme { Description = "Cabeçalho de autorização do JWT usando o esquema Bearer Exemplo: \"Authorization: Bearer {token}\"", Name = "Authorization", In = "header", Type = "apiKey" }); options.AddSecurityRequirement(new Dictionary <string, IEnumerable <string> > { { "Bearer", new string[] { } }, }); })); }
private async Task <T> HandleSynologyResponse <T>(IFlurlResponse httpResponse, IApiInfo apiInfo, string apiMethod) { switch (httpResponse.StatusCode) { case (int)HttpStatusCode.OK: var response = await httpResponse.GetJsonAsync <ApiResponse <T> >(); if (!response.Success) { var errorDescription = GetErrorMessage(response?.Error?.Code ?? 0, apiInfo.Name); throw new SynologyApiException(apiInfo, apiMethod, response.Error.Code, errorDescription); } if (typeof(T) == typeof(BaseApiResponse)) { return((T)Activator.CreateInstance(typeof(T), new object[] { response.Success })); } return(response.Data); default: throw new UnexpectedResponseStatusException((HttpStatusCode)httpResponse.StatusCode);; } }
public AuthorizeCheckOperationFilter(IApiInfo apiInfo) { _apiInfo = apiInfo; }