/// <summary>
 /// Instanciates a new request builder with provided (nullable) request
 /// middleware, a request method and url which will all be passed down to
 /// the request handler.
 /// </summary>
 /// <param name="requestMiddleware">The request middleware.</param>
 /// <param name="requestMethod">The request method.</param>
 /// <param name="url">The destination URL.</param>
 public RequestBuilder(RequestMiddleware requestMiddleware, RequestMethod requestMethod, string url)
 {
     this.requestMiddleware = requestMiddleware;
     this.requestHandler.SetRequestMiddleware(requestMiddleware: requestMiddleware);
     this.requestHandler.SetRequestMethod(requestMethod: requestMethod);
     this.requestHandler.SetUrl(url: url);
 }
示例#2
0
 public static Middleware Create(RequestHandler handler, RequestMiddleware[] requestModules, ResponseMiddleware[] responseModules)
 {
     Middleware m = new Middleware();
     m.RequestModules = requestModules;
     m.ResponseModules = responseModules;
     m.Handler = handler;
     return m;
 }
        // [Fact]
        public void Create_Middleware_From_Class_That_Implements_IRequestMiddleware()
        {
            RequestMiddleware middleware =
                ClassMiddlewareFactory.Create <CustomMiddlewareThatImplementsInterface>();
            var contextMock = new Mock <IRequestContext>();

            middleware.Invoke(c => Task.CompletedTask).Invoke(contextMock.Object);
        }
示例#4
0
        public RequestRunner(
            SystemHttpClient client,
            ITransmissionSettings transmissionSettings,
            IArrayFormatter arrayFormatter,
            CookieContainer cookieContainer,
            MiddlewareCollection middleware)
        {
            var defaultMiddleware = new RequestMiddleware(client, transmissionSettings, arrayFormatter, cookieContainer);

            middleware.Append(defaultMiddleware);
            middlewareHead = middleware.BuildMiddlewareChain();
        }
        public async Task contributor_not_executed()
        {
            Env.PipelineData.PipelineStage.CurrentState = PipelineContinuation.RenderNow;

            var middleware = new RequestMiddleware(
                Contributor(e => Task.FromResult(PipelineContinuation.Continue)))
                             .Compose(Next);
            await middleware.Invoke(Env);

            NextCalled.ShouldBeTrue();
            ContributorCalled.ShouldBeFalse();
        }
示例#6
0
        /// <summary>
        /// 启动服务器!
        /// </summary>
        /// <param name="message"></param>
        public async void Run(string message = "服务器运行起来了!")
        {
            if (Instance is null)
            {
                Instance = this;
            }
            else
            {
                Logger.Log("只允许同时启动一个服务器!", LogLevel.Warn);
                return;
            }
            // 处理未观察到的异常
            TaskScheduler.UnobservedTaskException += (sender, eventArgs) =>
            {
                eventArgs.SetObserved();
                (eventArgs.Exception).Handle(e =>
                {
                    Logger.Log($"Exception type: {e.GetType()}\n{e}", LogLevel.Error);
                    return(true);
                });
            };
            // 加载解析器
            Parser = new Parser(RequestHandleAsync, ResponseHandleAsync);
            // 加载中间件
            RequestMiddleware  = new RequestMiddleware(this);
            ResponseMiddleware = new ResponseMiddleware(this);
            // 初始化连接池 与最大连接数保持一致
            foreach (var i in Enumerable.Range(0, MaxConnection))
            {
                FreeClients.Enqueue(new Client(this));
            }
            // 初始化房间
            foreach (var i in Enumerable.Range(0, MaxRoomNumbers))
            {
                FreeRooms.Enqueue(new Room(i));
            }

            Logger.Log($"初始化了{FreeClients.Count}个对等客户端");
            // 设置请求队列的最大值
            Listener.Start(MaxConnection);
            Logger.Log(message);
            // Test
            for (int i = 1; i < 3; i++)
            {
                var room = GetRoom();
                room.Init(GetClient(), i, i * 2, $"TestRoom{i}");
            }

            //
            // 异步接受客户端连接请求
            await AcceptAsync();
        }
示例#7
0
        public async Task pipeline_is_in_RenderNow()
        {
            Env.PipelineData.PipelineStage.CurrentState = PipelineContinuation.Continue;
            var middleware = new RequestMiddleware(Contributor(e => Task.FromResult(PipelineContinuation.RenderNow)))
                             .Compose(Next);

            await middleware.Invoke(Env);

            ContributorCalled.ShouldBeTrue();
            NextCalled.ShouldBeTrue();

            Env.PipelineData.PipelineStage.CurrentState.ShouldBe(PipelineContinuation.RenderNow);
        }
        public async Task contributor_executed()
        {
            Env.PipelineData.PipelineStage.CurrentState = PipelineContinuation.Continue;

            var middleware = new RequestMiddleware(
                Contributor(e => { throw new InvalidOperationException("Should not throw"); }))
                             .Compose(Next);
            await middleware.Invoke(Env);

            ContributorCalled.ShouldBeTrue();
            NextCalled.ShouldBeTrue();

            Env.PipelineData.PipelineStage.CurrentState.ShouldBe(PipelineContinuation.Abort);
        }
示例#9
0
        private async Task RequestHandleAsync(IRequest request)
        {
            await Task.Run(() => RequestHandle());

            void RequestHandle()
            {
                // 请求中间件
                RequestMiddleware.BeforeWrapper(request);
                // 让控制器管理者去处理请求
                var response = ControllerManager.RequestHandler(request);

                // 响应中间件
                ResponseMiddleware.AfterWrapper(response);
                // 向客户端发送响应
                request.Client.SendMessage(Message.GetBytes(response));
            }
        }
    /// <summary>
    /// Adds a delegate that will be used to create a middleware for the execution pipeline.
    /// </summary>
    /// <param name="builder">The <see cref="IRequestExecutorBuilder"/>.</param>
    /// <param name="middleware">A delegate that is used to create a middleware for the execution pipeline.</param>
    /// <returns>An <see cref="IRequestExecutorBuilder"/> that can be used to configure a schema and its execution.</returns>
    public static IRequestExecutorBuilder UseRequest(
        this IRequestExecutorBuilder builder,
        RequestMiddleware middleware)
    {
        if (builder is null)
        {
            throw new ArgumentNullException(nameof(builder));
        }

        if (middleware is null)
        {
            throw new ArgumentNullException(nameof(middleware));
        }

        return(Configure(
                   builder,
                   options => options.Pipeline.Add((context, next) => middleware(next))));
    }
示例#11
0
 /// Sets the requestMiddleware for this requestHandler to use when creating
 /// request or manipulating data.
 internal void SetRequestMiddleware(RequestMiddleware requestMiddleware)
 {
     this.requestMiddleware = requestMiddleware;
 }