/// <summary> /// When overrided in the sub class, which can be used to implement a custom hnandler /// </summary> /// <param name="context"></param> protected virtual Task ProcessRequestAsync(HttpListenerContext context) { if (string.IsNullOrEmpty(context.Request.RawUrl)) { return(TypeConstants.EmptyTask); } RequestContext.Instance.StartRequestContext(); var operationName = context.Request.GetOperationName().UrlDecode(); var httpReq = context.ToRequest(operationName); var httpRes = httpReq.Response; var handler = HttpHandlerFactory.GetHandler(httpReq); var serviceStackHandler = handler as IServiceStackHandler; if (serviceStackHandler == null) { throw new NotImplementedException($"Cannot execute handler: {handler} at PathInfo: {httpReq.PathInfo}"); } var task = serviceStackHandler.ProcessRequestAsync(httpReq, httpRes, operationName); return(HostContext.Async.ContinueWith(httpReq, task, x => httpRes.Close(), TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.AttachedToParent)); //Matches Exceptions handled in HttpListenerBase.InitTask() }
protected virtual string GetReferrerUrl(IServiceBase authService, IAuthSession session, Authenticate request = null) { if (request == null) { request = authService.Request.Dto as Authenticate; } var referrerUrl = session.ReferrerUrl; if (referrerUrl.IsNullOrEmpty()) { referrerUrl = (request != null ? request.Continue : null) ?? authService.Request.GetHeader("Referer"); } var requestUri = authService.Request.AbsoluteUri; if (referrerUrl.IsNullOrEmpty() || referrerUrl.IndexOf("/auth", StringComparison.OrdinalIgnoreCase) >= 0) { referrerUrl = this.RedirectUrl ?? HttpHandlerFactory.GetBaseUrl() ?? requestUri.Substring(0, requestUri.IndexOf("/", "https://".Length + 1, StringComparison.Ordinal)); } return(referrerUrl); }
/// <summary> /// This is a custom method to register the HttpClient and typed factory. Needed because we need to access the config name when creating the typed client /// </summary> private static IHttpClientBuilder AddGrpcHttpClient <TClient>(this IServiceCollection services, string name) where TClient : class { if (services == null) { throw new ArgumentNullException(nameof(services)); } services .AddHttpClient(name) .ConfigurePrimaryHttpMessageHandler(() => { // Set PrimaryHandler to null so we can track whether the user // set a value or not. If they didn't set their own handler then // one will be created by PostConfigure. return(null); }); services.PostConfigure <HttpClientFactoryOptions>(name, options => { options.HttpMessageHandlerBuilderActions.Add(static builder => { if (builder.PrimaryHandler == null) { // This will throw in .NET Standard 2.0 with a prompt that a user must set a handler. // Because it throws it should only be called in PostConfigure if no handler has been set. var handler = HttpHandlerFactory.CreatePrimaryHandler(); #if NET5_0 handler = HttpHandlerFactory.EnsureTelemetryHandler(handler); #endif builder.PrimaryHandler = handler; } }); });
protected IAuthTokens Init(IServiceBase authService, ref IAuthSession session, Authenticate request) { var requestUri = authService.Request.AbsoluteUri; if (this.CallbackUrl.IsNullOrEmpty()) { this.CallbackUrl = requestUri; } if (session.ReferrerUrl.IsNullOrEmpty()) { session.ReferrerUrl = (request != null ? request.Continue : null) ?? authService.Request.GetHeader("Referer"); } if (session.ReferrerUrl.IsNullOrEmpty() || session.ReferrerUrl.IndexOf("/auth", StringComparison.OrdinalIgnoreCase) >= 0) { session.ReferrerUrl = this.RedirectUrl ?? HttpHandlerFactory.GetBaseUrl() ?? requestUri.Substring(0, requestUri.IndexOf("/", "https://".Length + 1, StringComparison.Ordinal)); } var tokens = session.ProviderOAuthAccess.FirstOrDefault(x => x.Provider == this.Provider); if (tokens == null) { session.ProviderOAuthAccess.Add(tokens = new AuthTokens { Provider = this.Provider }); } return(tokens); }
internal GrpcChannel(Uri address, GrpcChannelOptions channelOptions) : base(address.Authority) { _methodInfoCache = new ConcurrentDictionary <IMethod, GrpcMethodInfo>(); // Dispose the HTTP client/handler if... // 1. No client/handler was specified and so the channel created the client itself // 2. User has specified a client/handler and set DisposeHttpClient to true _shouldDisposeHttpClient = (channelOptions.HttpClient == null && channelOptions.HttpHandler == null) || channelOptions.DisposeHttpClient; Address = address; HttpInvoker = channelOptions.HttpClient ?? CreateInternalHttpInvoker(channelOptions.HttpHandler); IsWinHttp = channelOptions.HttpHandler != null?HttpHandlerFactory.HasHttpHandlerType(channelOptions.HttpHandler, "System.Net.Http.WinHttpHandler") : false; SendMaxMessageSize = channelOptions.MaxSendMessageSize; ReceiveMaxMessageSize = channelOptions.MaxReceiveMessageSize; CompressionProviders = ResolveCompressionProviders(channelOptions.CompressionProviders); MessageAcceptEncoding = GrpcProtocolHelpers.GetMessageAcceptEncoding(CompressionProviders); LoggerFactory = channelOptions.LoggerFactory ?? NullLoggerFactory.Instance; ThrowOperationCanceledOnCancellation = channelOptions.ThrowOperationCanceledOnCancellation; _createMethodInfoFunc = CreateMethodInfo; ActiveCalls = new HashSet <IDisposable>(); if (channelOptions.Credentials != null) { var configurator = new DefaultChannelCredentialsConfigurator(); channelOptions.Credentials.InternalPopulateConfiguration(configurator, null); IsSecure = configurator.IsSecure; CallCredentials = configurator.CallCredentials; ValidateChannelCredentials(); } }
/// <summary> /// This is a custom method to register the HttpClient and typed factory. Needed because we need to access the config name when creating the typed client /// </summary> private static IHttpClientBuilder AddGrpcHttpClient <TClient>(this IServiceCollection services, string name) where TClient : class { if (services == null) { throw new ArgumentNullException(nameof(services)); } services .AddHttpClient(name) .ConfigurePrimaryHttpMessageHandler(() => { var handler = HttpHandlerFactory.CreatePrimaryHandler(); #if NET5_0 handler = HttpHandlerFactory.EnsureTelemetryHandler(handler); #endif return(handler); }); var builder = new DefaultHttpClientBuilder(services, name); builder.Services.AddTransient <TClient>(s => { var clientFactory = s.GetRequiredService <GrpcClientFactory>(); return(clientFactory.CreateClient <TClient>(builder.Name)); }); ReserveClient(builder, typeof(TClient), name); return(builder); }
/// <summary> /// Overridable method that can be used to implement a custom hnandler /// </summary> /// <param name="context"></param> protected Task ProcessRequestAsync(HttpListenerContext context) { if (string.IsNullOrEmpty(context.Request.RawUrl)) { return(((object)null).AsTaskResult()); } var operationName = context.Request.GetOperationName(); var httpReq = context.ToRequest(operationName); var httpRes = httpReq.Response; var handler = HttpHandlerFactory.GetHandler(httpReq); var serviceStackHandler = handler as IServiceStackHandler; if (serviceStackHandler != null) { var restHandler = serviceStackHandler as RestHandler; if (restHandler != null) { httpReq.OperationName = operationName = restHandler.RestPath.RequestType.GetOperationName(); } var task = serviceStackHandler.ProcessRequestAsync(httpReq, httpRes, operationName); task.ContinueWith(x => httpRes.Close()); return(task); } return(new NotImplementedException("Cannot execute handler: " + handler + " at PathInfo: " + httpReq.PathInfo) .AsTaskException()); }
public void Resolves_the_right_handler_for_expexted_paths() { foreach (var item in pathInfoMap) { var expectedType = item.Value; var handler = HttpHandlerFactory.GetHandlerForPathInfo(null, item.Key, null, null); Assert.That(handler.GetType(), Is.EqualTo(expectedType)); } }
private static ServiceStackHandlerBase GetHandler(IHttpRequest httpReq) { var httpHandler = HttpHandlerFactory.GetHandlerForPathInfo(httpReq, null) as ServiceStackHandlerBase; if (httpHandler == null) { throw new NotSupportedException(httpReq.PathInfo); } return(httpHandler); }
private static ServiceStackHandlerBase GetHandler(string httpMethod, string pathInfo) { var httpHandler = HttpHandlerFactory.GetHandlerForPathInfo(httpMethod, pathInfo, pathInfo, null) as ServiceStackHandlerBase; if (httpHandler == null) { throw new NotSupportedException(pathInfo); } return(httpHandler); }
public void GetHandlerReturnsNull() { var dependancyResolverMock = new Mock <IDependencyResolver>(); var handler = _fixture.Create <PlanningPokerWebSocketHandler>(); dependancyResolverMock.Setup(x => x.Resolve <PlanningPokerWebSocketHandler>()).Returns(handler); var factory = new HttpHandlerFactory(dependancyResolverMock.Object); var result = factory.GetHandler(null, "get", "/", ""); Assert.IsNull(result); }
public void Resolves_the_right_handler_for_case_insensitive_expexted_paths() { foreach (var item in pathInfoMap) { var expectedType = item.Value; var lowerPathInfo = item.Key.ToLower(); lowerPathInfo.Print(); var handler = HttpHandlerFactory.GetHandlerForPathInfo(null, lowerPathInfo, null, null); Assert.That(handler.GetType(), Is.EqualTo(expectedType)); } }
private void InternalInit(ServerOption option) { if (_option != null) { throw new InvalidOperationException("不要重复调用Run方法。"); } ServerOptionValidator validator = new ServerOptionValidator(); validator.Validate(option); validator.SetDefaultValues(option); if (option.HandlerTypes != null) { // 注册HttpHandlerFactory foreach (Type handlerType in option.HandlerTypes) { var factory = Activator.CreateInstance(handlerType) as IHttpHandlerFactory; HttpHandlerFactory.GetInstance().RegisterFactory(factory); ExecuuteServerHostInit(option, handlerType); } } if (option.ModuleTypes != null) { // 注册HttpModule foreach (Type moduleType in option.ModuleTypes) { ExtenderManager.RegisterSubscriber(moduleType); ExecuuteServerHostInit(option, moduleType); } } // 加载当前目录下的所有程序集 AssemblyLoader.LoadAssemblies(AppDomain.CurrentDomain.BaseDirectory); // 加载所有路由规则 RoutingManager.Instance.LoadRoutes(); _option = option; // 启动后台线程响应所有请求 _workThread = new Thread(ServerProc); _workThread.IsBackground = true; _workThread.Start(); // 创建HttpListener实例并初始化 this.Start(); }
public object Get(ResetUserAuth request) { this.Cache.Remove(SessionFeature.GetSessionKey(Request)); Db.DeleteAll <UserAuth>(); Db.DeleteAll <UserAuthDetails>(); var referrer = Request.UrlReferrer != null ? Request.UrlReferrer.AbsoluteUri : HttpHandlerFactory.GetBaseUrl(); return(HttpResult.Redirect(referrer)); }
internal GrpcChannel(Uri address, GrpcChannelOptions channelOptions) : base(address.Authority) { _lock = new object(); _methodInfoCache = new ConcurrentDictionary <IMethod, GrpcMethodInfo>(); // Dispose the HTTP client/handler if... // 1. No client/handler was specified and so the channel created the client itself // 2. User has specified a client/handler and set DisposeHttpClient to true _shouldDisposeHttpClient = (channelOptions.HttpClient == null && channelOptions.HttpHandler == null) || channelOptions.DisposeHttpClient; Address = address; HttpInvoker = channelOptions.HttpClient ?? CreateInternalHttpInvoker(channelOptions.HttpHandler); IsWinHttp = channelOptions.HttpHandler != null?HttpHandlerFactory.HasHttpHandlerType(channelOptions.HttpHandler, "System.Net.Http.WinHttpHandler") : false; SendMaxMessageSize = channelOptions.MaxSendMessageSize; ReceiveMaxMessageSize = channelOptions.MaxReceiveMessageSize; MaxRetryAttempts = channelOptions.MaxRetryAttempts; MaxRetryBufferSize = channelOptions.MaxRetryBufferSize; MaxRetryBufferPerCallSize = channelOptions.MaxRetryBufferPerCallSize; CompressionProviders = ResolveCompressionProviders(channelOptions.CompressionProviders); MessageAcceptEncoding = GrpcProtocolHelpers.GetMessageAcceptEncoding(CompressionProviders); LoggerFactory = channelOptions.LoggerFactory ?? NullLoggerFactory.Instance; Logger = LoggerFactory.CreateLogger <GrpcChannel>(); ThrowOperationCanceledOnCancellation = channelOptions.ThrowOperationCanceledOnCancellation; _createMethodInfoFunc = CreateMethodInfo; ActiveCalls = new HashSet <IDisposable>(); if (channelOptions.ServiceConfig is { } serviceConfig) { RetryThrottling = serviceConfig.RetryThrottling != null?CreateChannelRetryThrottling(serviceConfig.RetryThrottling) : null; _serviceConfigMethods = CreateServiceConfigMethods(serviceConfig); _random = new Random(); } if (channelOptions.Credentials != null) { var configurator = new DefaultChannelCredentialsConfigurator(); channelOptions.Credentials.InternalPopulateConfiguration(configurator, null); IsSecure = configurator.IsSecure; CallCredentials = configurator.CallCredentials; ValidateChannelCredentials(); } if (!string.IsNullOrEmpty(Address.PathAndQuery) && Address.PathAndQuery != "/") { Log.AddressPathUnused(Logger, Address.OriginalString); } }
public void Go() { var http = Substitute.For<HttpContextBase>(); http.Request.HttpMethod.Returns("GET"); http.Request.Path.Returns("/Product/12345"); var factory = new HttpHandlerFactory(typeof(SimpleService).Assembly); System.Console.WriteLine(factory.Routes.Count()); var handler = factory.MapHandler(http); Assert.IsTrue(handler is HttpServiceHandler); var serviceHandler = handler as HttpServiceHandler; Assert.AreEqual("/Product/{ProductId}", serviceHandler.Route.Route); }
public void Go() { var http = Substitute.For <HttpContextBase>(); http.Request.HttpMethod.Returns("GET"); http.Request.Path.Returns("/Product/12345"); var factory = new HttpHandlerFactory(typeof(SimpleService).Assembly); System.Console.WriteLine(factory.Routes.Count()); var handler = factory.MapHandler(http); Assert.IsTrue(handler is HttpServiceHandler); var serviceHandler = handler as HttpServiceHandler; Assert.AreEqual("/Product/{ProductId}", serviceHandler.Route.Route); }
private static HttpMessageInvoker CreateInternalHttpInvoker(HttpMessageHandler?handler) { // HttpMessageInvoker should always dispose handler if Disposed is called on it. // Decision to dispose invoker is controlled by _shouldDisposeHttpClient. if (handler == null) { handler = HttpHandlerFactory.CreatePrimaryHandler(); } #if NET5_0 handler = HttpHandlerFactory.EnsureTelemetryHandler(handler); #endif // Use HttpMessageInvoker instead of HttpClient because it is faster // and we don't need client's features. var httpInvoker = new HttpMessageInvoker(handler, disposeHandler: true); return(httpInvoker); }
private void OnGetContext(object ctx) { if (shutdownInProgress) { return; } try { var context = (HttpListenerContext)ctx; var conn = new Connection(this, context); if (!Thread.CurrentThread.CurrentCulture.Equals(currentThreadCulture)) { Thread.CurrentThread.CurrentCulture = currentThreadCulture; Thread.CurrentThread.CurrentUICulture = currentThreadCulture; } if (conn.WaitForRequestBytes() == 0) { conn.WriteErrorAndClose(400); } else { var host = GetHost(); if (host == null) { conn.WriteErrorAndClose(500); } else { var handlerContext = new HttpHandlerContext(this, host, conn, Thread.CurrentPrincipal.Identity); HttpHandlerFactory.GetHttpHandler(handlerContext) .ProcessRequest(handlerContext); } } } catch (Exception ex) { log.Warn(ServerMessages.ExceptionWhileProcessing, ex); } }
public void Does_allow_valid_FilePaths() { using (new BasicAppHost { ConfigFilter = config => { config.AllowFileExtensions.Add("aaa"); config.AllowFilePaths.Add("dir/**/*.zzz"); } }.Init()) { Assert.That(HttpHandlerFactory.ShouldAllow("a.js")); Assert.That(HttpHandlerFactory.ShouldAllow("a.aaa")); Assert.That(HttpHandlerFactory.ShouldAllow("dir/a/b/c/a.aaa")); Assert.That(!HttpHandlerFactory.ShouldAllow("a.zzz")); Assert.That(HttpHandlerFactory.ShouldAllow("dir/a.zzz")); Assert.That(HttpHandlerFactory.ShouldAllow("dir/a/b/c/a.zzz")); Assert.That(!HttpHandlerFactory.ShouldAllow("a.json")); Assert.That(HttpHandlerFactory.ShouldAllow("jspm_packages/a.json")); Assert.That(HttpHandlerFactory.ShouldAllow("jspm_packages/a/b/c/a.json")); } }
/// <summary> /// Overridable method that can be used to implement a custom hnandler /// </summary> /// <param name="httpReq">The HTTP req.</param> /// <param name="url">The URL.</param> /// <returns>Task.</returns> protected async Task RequestHandler(IHttpRequest httpReq, Uri url) { var date = DateTime.Now; var httpRes = httpReq.Response; if (_disposed) { httpRes.StatusCode = 503; httpRes.Close(); return; } if (!ValidateHost(url)) { httpRes.StatusCode = 400; httpRes.ContentType = "text/plain"; httpRes.Write("Invalid host"); httpRes.Close(); return; } if (string.Equals(httpReq.Verb, "OPTIONS", StringComparison.OrdinalIgnoreCase)) { httpRes.StatusCode = 200; httpRes.AddHeader("Access-Control-Allow-Origin", "*"); httpRes.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, PATCH, OPTIONS"); httpRes.AddHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, Range, X-MediaBrowser-Token, X-Emby-Authorization"); httpRes.ContentType = "text/html"; httpRes.Close(); } var operationName = httpReq.OperationName; var localPath = url.LocalPath; var urlString = url.OriginalString; var enableLog = EnableLogging(urlString, localPath); var urlToLog = urlString; if (enableLog) { urlToLog = GetUrlToLog(urlString); LoggerUtils.LogRequest(_logger, urlToLog, httpReq.HttpMethod, httpReq.UserAgent); } if (string.Equals(localPath, "/emby/", StringComparison.OrdinalIgnoreCase) || string.Equals(localPath, "/mediabrowser/", StringComparison.OrdinalIgnoreCase)) { httpRes.RedirectToUrl(DefaultRedirectPath); return; } if (string.Equals(localPath, "/emby", StringComparison.OrdinalIgnoreCase) || string.Equals(localPath, "/mediabrowser", StringComparison.OrdinalIgnoreCase)) { httpRes.RedirectToUrl("emby/" + DefaultRedirectPath); return; } if (string.Equals(localPath, "/mediabrowser/", StringComparison.OrdinalIgnoreCase) || string.Equals(localPath, "/mediabrowser", StringComparison.OrdinalIgnoreCase) || localPath.IndexOf("mediabrowser/web", StringComparison.OrdinalIgnoreCase) != -1) { httpRes.StatusCode = 200; httpRes.ContentType = "text/html"; var newUrl = urlString.Replace("mediabrowser", "emby", StringComparison.OrdinalIgnoreCase) .Replace("/dashboard/", "/web/", StringComparison.OrdinalIgnoreCase); if (!string.Equals(newUrl, urlString, StringComparison.OrdinalIgnoreCase)) { httpRes.Write("<!doctype html><html><head><title>Emby</title></head><body>Please update your Emby bookmark to <a href=\"" + newUrl + "\">" + newUrl + "</a></body></html>"); httpRes.Close(); return; } } if (localPath.IndexOf("dashboard/", StringComparison.OrdinalIgnoreCase) != -1 && localPath.IndexOf("web/dashboard", StringComparison.OrdinalIgnoreCase) == -1) { httpRes.StatusCode = 200; httpRes.ContentType = "text/html"; var newUrl = urlString.Replace("mediabrowser", "emby", StringComparison.OrdinalIgnoreCase) .Replace("/dashboard/", "/web/", StringComparison.OrdinalIgnoreCase); if (!string.Equals(newUrl, urlString, StringComparison.OrdinalIgnoreCase)) { httpRes.Write("<!doctype html><html><head><title>Emby</title></head><body>Please update your Emby bookmark to <a href=\"" + newUrl + "\">" + newUrl + "</a></body></html>"); httpRes.Close(); return; } } if (string.Equals(localPath, "/web", StringComparison.OrdinalIgnoreCase)) { httpRes.RedirectToUrl(DefaultRedirectPath); return; } if (string.Equals(localPath, "/web/", StringComparison.OrdinalIgnoreCase)) { httpRes.RedirectToUrl("../" + DefaultRedirectPath); return; } if (string.Equals(localPath, "/", StringComparison.OrdinalIgnoreCase)) { httpRes.RedirectToUrl(DefaultRedirectPath); return; } if (string.IsNullOrEmpty(localPath)) { httpRes.RedirectToUrl("/" + DefaultRedirectPath); return; } if (string.Equals(localPath, "/emby/pin", StringComparison.OrdinalIgnoreCase)) { httpRes.RedirectToUrl("web/pin.html"); return; } if (!string.IsNullOrWhiteSpace(GlobalResponse)) { httpRes.StatusCode = 503; httpRes.ContentType = "text/html"; httpRes.Write(GlobalResponse); httpRes.Close(); return; } var handler = HttpHandlerFactory.GetHandler(httpReq); var remoteIp = httpReq.RemoteIp; var serviceStackHandler = handler as IServiceStackHandler; if (serviceStackHandler != null) { var restHandler = serviceStackHandler as RestHandler; if (restHandler != null) { httpReq.OperationName = operationName = restHandler.RestPath.RequestType.GetOperationName(); } try { await serviceStackHandler.ProcessRequestAsync(httpReq, httpRes, operationName).ConfigureAwait(false); } finally { httpRes.Close(); var statusCode = httpRes.StatusCode; var duration = DateTime.Now - date; if (enableLog) { LoggerUtils.LogResponse(_logger, statusCode, urlToLog, remoteIp, duration); } } } throw new NotImplementedException("Cannot execute handler: " + handler + " at PathInfo: " + httpReq.PathInfo); }
/// <summary> /// Overridable method that can be used to implement a custom hnandler /// </summary> /// <param name="httpReq">The HTTP req.</param> /// <param name="url">The URL.</param> /// <returns>Task.</returns> protected Task RequestHandler(IHttpRequest httpReq, Uri url) { var date = DateTime.Now; var httpRes = httpReq.Response; var operationName = httpReq.OperationName; var localPath = url.LocalPath; if (string.Equals(localPath, "/mediabrowser/", StringComparison.OrdinalIgnoreCase) || string.Equals(localPath, "/emby/", StringComparison.OrdinalIgnoreCase)) { httpRes.RedirectToUrl(DefaultRedirectPath); return(Task.FromResult(true)); } if (string.Equals(localPath, "/mediabrowser", StringComparison.OrdinalIgnoreCase)) { httpRes.RedirectToUrl("mediabrowser/" + DefaultRedirectPath); return(Task.FromResult(true)); } if (string.Equals(localPath, "/emby", StringComparison.OrdinalIgnoreCase)) { httpRes.RedirectToUrl("emby/" + DefaultRedirectPath); return(Task.FromResult(true)); } if (string.Equals(localPath, "/", StringComparison.OrdinalIgnoreCase)) { httpRes.RedirectToUrl(DefaultRedirectPath); return(Task.FromResult(true)); } if (string.IsNullOrEmpty(localPath)) { httpRes.RedirectToUrl("/" + DefaultRedirectPath); return(Task.FromResult(true)); } var handler = HttpHandlerFactory.GetHandler(httpReq); var remoteIp = httpReq.RemoteIp; var serviceStackHandler = handler as IServiceStackHandler; if (serviceStackHandler != null) { var restHandler = serviceStackHandler as RestHandler; if (restHandler != null) { httpReq.OperationName = operationName = restHandler.RestPath.RequestType.GetOperationName(); } var task = serviceStackHandler.ProcessRequestAsync(httpReq, httpRes, operationName); task.ContinueWith(x => httpRes.Close(), TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.AttachedToParent); //Matches Exceptions handled in HttpListenerBase.InitTask() var urlString = url.ToString(); task.ContinueWith(x => { var statusCode = httpRes.StatusCode; var duration = DateTime.Now - date; LoggerUtils.LogResponse(_logger, statusCode, urlString, remoteIp, duration); }, TaskContinuationOptions.None); return(task); } return(new NotImplementedException("Cannot execute handler: " + handler + " at PathInfo: " + httpReq.PathInfo) .AsTaskException()); }
/// <summary> /// Overridable method that can be used to implement a custom hnandler /// </summary> /// <param name="httpReq">The HTTP req.</param> /// <param name="url">The URL.</param> /// <returns>Task.</returns> protected Task RequestHandler(IHttpRequest httpReq, Uri url) { var date = DateTime.Now; var httpRes = httpReq.Response; var operationName = httpReq.OperationName; var localPath = url.LocalPath; var urlString = url.OriginalString; var enableLog = EnableLogging(urlString, localPath); var urlToLog = urlString; if (enableLog) { urlToLog = GetUrlToLog(urlString); LoggerUtils.LogRequest(_logger, urlToLog, httpReq.HttpMethod, httpReq.UserAgent); } if (string.Equals(localPath, "/emby/", StringComparison.OrdinalIgnoreCase) || string.Equals(localPath, "/mediabrowser/", StringComparison.OrdinalIgnoreCase)) { httpRes.RedirectToUrl(DefaultRedirectPath); return(Task.FromResult(true)); } if (string.Equals(localPath, "/emby", StringComparison.OrdinalIgnoreCase) || string.Equals(localPath, "/mediabrowser", StringComparison.OrdinalIgnoreCase)) { httpRes.RedirectToUrl("emby/" + DefaultRedirectPath); return(Task.FromResult(true)); } if (string.Equals(localPath, "/mediabrowser/", StringComparison.OrdinalIgnoreCase) || string.Equals(localPath, "/mediabrowser", StringComparison.OrdinalIgnoreCase) || localPath.IndexOf("mediabrowser/web", StringComparison.OrdinalIgnoreCase) != -1 || localPath.IndexOf("dashboard/", StringComparison.OrdinalIgnoreCase) != -1) { httpRes.StatusCode = 200; httpRes.ContentType = "text/html"; var newUrl = urlString.Replace("mediabrowser", "emby", StringComparison.OrdinalIgnoreCase) .Replace("/dashboard/", "/web/", StringComparison.OrdinalIgnoreCase); if (!string.Equals(newUrl, urlString, StringComparison.OrdinalIgnoreCase)) { httpRes.Write("<!doctype html><html><head><title>Emby</title></head><body>Please update your Emby bookmark to <a href=\"" + newUrl + "\">" + newUrl + "</a></body></html>"); httpRes.Close(); return(Task.FromResult(true)); } } if (string.Equals(localPath, "/web", StringComparison.OrdinalIgnoreCase)) { httpRes.RedirectToUrl(DefaultRedirectPath); return(Task.FromResult(true)); } if (string.Equals(localPath, "/web/", StringComparison.OrdinalIgnoreCase)) { httpRes.RedirectToUrl("../" + DefaultRedirectPath); return(Task.FromResult(true)); } if (string.Equals(localPath, "/", StringComparison.OrdinalIgnoreCase)) { httpRes.RedirectToUrl(DefaultRedirectPath); return(Task.FromResult(true)); } if (string.IsNullOrEmpty(localPath)) { httpRes.RedirectToUrl("/" + DefaultRedirectPath); return(Task.FromResult(true)); } if (string.Equals(localPath, "/emby/pin", StringComparison.OrdinalIgnoreCase)) { httpRes.RedirectToUrl("web/pin.html"); return(Task.FromResult(true)); } if (!string.IsNullOrWhiteSpace(GlobalResponse)) { httpRes.StatusCode = 503; httpRes.ContentType = "text/html"; httpRes.Write(GlobalResponse); httpRes.Close(); return(Task.FromResult(true)); } var handler = HttpHandlerFactory.GetHandler(httpReq); var remoteIp = httpReq.RemoteIp; var serviceStackHandler = handler as IServiceStackHandler; if (serviceStackHandler != null) { var restHandler = serviceStackHandler as RestHandler; if (restHandler != null) { httpReq.OperationName = operationName = restHandler.RestPath.RequestType.GetOperationName(); } var task = serviceStackHandler.ProcessRequestAsync(httpReq, httpRes, operationName); task.ContinueWith(x => httpRes.Close(), TaskContinuationOptions.OnlyOnRanToCompletion | TaskContinuationOptions.AttachedToParent); //Matches Exceptions handled in HttpListenerBase.InitTask() task.ContinueWith(x => { var statusCode = httpRes.StatusCode; var duration = DateTime.Now - date; if (enableLog) { LoggerUtils.LogResponse(_logger, statusCode, urlToLog, remoteIp, duration); } }, TaskContinuationOptions.None); return(task); } return(new NotImplementedException("Cannot execute handler: " + handler + " at PathInfo: " + httpReq.PathInfo) .AsTaskException()); }
/// <inheritdoc/> public HttpTunnelConfigurableFactory(IEventClient client, IWebProxy proxy, IJsonSerializer serializer, IEnumerable <IHttpHandler> handlers, ILogger logger) { _tunnel = new HttpTunnelHandlerFactory(client, serializer, handlers, logger); _fallback = new HttpHandlerFactory(handlers, proxy, logger); }
/// <summary> /// Overridable method that can be used to implement a custom hnandler /// </summary> /// <param name="httpReq">The HTTP req.</param> /// <param name="url">The URL.</param> /// <returns>Task.</returns> protected async Task RequestHandler(IHttpRequest httpReq, Uri url) { var date = DateTime.Now; var httpRes = httpReq.Response; bool enableLog = false; string urlToLog = null; string remoteIp = null; try { if (_disposed) { httpRes.StatusCode = 503; httpRes.ContentType = "text/plain"; Write(httpRes, "Server shutting down"); return; } if (!ValidateHost(url)) { httpRes.StatusCode = 400; httpRes.ContentType = "text/plain"; Write(httpRes, "Invalid host"); return; } if (string.Equals(httpReq.Verb, "OPTIONS", StringComparison.OrdinalIgnoreCase)) { httpRes.StatusCode = 200; httpRes.AddHeader("Access-Control-Allow-Origin", "*"); httpRes.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, PATCH, OPTIONS"); httpRes.AddHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, Range, X-MediaBrowser-Token, X-Emby-Authorization"); httpRes.ContentType = "text/plain"; Write(httpRes, string.Empty); return; } var operationName = httpReq.OperationName; var localPath = url.LocalPath; var urlString = url.OriginalString; enableLog = EnableLogging(urlString, localPath); urlToLog = urlString; if (enableLog) { urlToLog = GetUrlToLog(urlString); remoteIp = httpReq.RemoteIp; LoggerUtils.LogRequest(_logger, urlToLog, httpReq.HttpMethod, httpReq.UserAgent); } if (string.Equals(localPath, "/emby/", StringComparison.OrdinalIgnoreCase) || string.Equals(localPath, "/mediabrowser/", StringComparison.OrdinalIgnoreCase)) { RedirectToUrl(httpRes, DefaultRedirectPath); return; } if (string.Equals(localPath, "/emby", StringComparison.OrdinalIgnoreCase) || string.Equals(localPath, "/mediabrowser", StringComparison.OrdinalIgnoreCase)) { RedirectToUrl(httpRes, "emby/" + DefaultRedirectPath); return; } if (string.Equals(localPath, "/mediabrowser/", StringComparison.OrdinalIgnoreCase) || string.Equals(localPath, "/mediabrowser", StringComparison.OrdinalIgnoreCase) || localPath.IndexOf("mediabrowser/web", StringComparison.OrdinalIgnoreCase) != -1) { httpRes.StatusCode = 200; httpRes.ContentType = "text/html"; var newUrl = urlString.Replace("mediabrowser", "emby", StringComparison.OrdinalIgnoreCase) .Replace("/dashboard/", "/web/", StringComparison.OrdinalIgnoreCase); if (!string.Equals(newUrl, urlString, StringComparison.OrdinalIgnoreCase)) { Write(httpRes, "<!doctype html><html><head><title>Emby</title></head><body>Please update your Emby bookmark to <a href=\"" + newUrl + "\">" + newUrl + "</a></body></html>"); return; } } if (localPath.IndexOf("dashboard/", StringComparison.OrdinalIgnoreCase) != -1 && localPath.IndexOf("web/dashboard", StringComparison.OrdinalIgnoreCase) == -1) { httpRes.StatusCode = 200; httpRes.ContentType = "text/html"; var newUrl = urlString.Replace("mediabrowser", "emby", StringComparison.OrdinalIgnoreCase) .Replace("/dashboard/", "/web/", StringComparison.OrdinalIgnoreCase); if (!string.Equals(newUrl, urlString, StringComparison.OrdinalIgnoreCase)) { Write(httpRes, "<!doctype html><html><head><title>Emby</title></head><body>Please update your Emby bookmark to <a href=\"" + newUrl + "\">" + newUrl + "</a></body></html>"); return; } } if (string.Equals(localPath, "/web", StringComparison.OrdinalIgnoreCase)) { RedirectToUrl(httpRes, DefaultRedirectPath); return; } if (string.Equals(localPath, "/web/", StringComparison.OrdinalIgnoreCase)) { RedirectToUrl(httpRes, "../" + DefaultRedirectPath); return; } if (string.Equals(localPath, "/", StringComparison.OrdinalIgnoreCase)) { RedirectToUrl(httpRes, DefaultRedirectPath); return; } if (string.IsNullOrEmpty(localPath)) { RedirectToUrl(httpRes, "/" + DefaultRedirectPath); return; } if (string.Equals(localPath, "/emby/pin", StringComparison.OrdinalIgnoreCase)) { RedirectToUrl(httpRes, "web/pin.html"); return; } if (!string.IsNullOrWhiteSpace(GlobalResponse)) { httpRes.StatusCode = 503; httpRes.ContentType = "text/html"; Write(httpRes, GlobalResponse); return; } var handler = HttpHandlerFactory.GetHandler(httpReq, _logger); if (handler != null) { await handler.ProcessRequestAsync(httpReq, httpRes, operationName).ConfigureAwait(false); } else { ErrorHandler(new FileNotFoundException(), httpReq); } } catch (OperationCanceledException ex) { ErrorHandler(ex, httpReq, false); } catch (Exception ex) { ErrorHandler(ex, httpReq); } finally { httpRes.Close(); if (enableLog) { var statusCode = httpRes.StatusCode; var duration = DateTime.Now - date; LoggerUtils.LogResponse(_logger, statusCode, urlToLog, remoteIp, duration); } } }