Exemplo n.º 1
0
            private static async Task ExecuteAsync(
                IDictionary <string, object> environment,
                IDictionary <string, string> keys, OwinRequest request,
                AsyncHttpRequestHandler handler)
            {
                var response = new OwinResponse(environment);

                var executor = (Func <Task <object> >)(async() =>
                {
                    var form = from w in request.HasForm()
                                         ? (IEnumerable <KeyValuePair <string, string[]> >)(await request.ReadFormAsync().ConfigureAwait(false))
                                         : EmptyForm
                               select w != null ? w[0] : null;

                    return(await handler.Executor(
                               environment,
                               keys,
                               form.ToDictionary()));
                });

                var result = await executor().ConfigureAwait(false);

                if (result != null)
                {
                    await response.WriteAsync(JsonConvert.SerializeObject(result)).ConfigureAwait(false);
                }

                response.StatusCode = handler.StatusCodeGenerator != null
                                    ? handler.StatusCodeGenerator(result)
                                    : (int)HttpStatusCode.OK;
            }
Exemplo n.º 2
0
        public Task Invoke(IDictionary <string, object> environment)
        {
            var request = new OwinRequest(environment);

            if (string.IsNullOrEmpty(_options.Path) || string.Equals(request.Path, _options.Path, StringComparison.OrdinalIgnoreCase))
            {
                // TODO: Make it pretty
                OwinResponse response = new OwinResponse(environment);
                response.ContentType = "text/html";

                StringBuilder builder = new StringBuilder();
                builder.AppendLine("<html>")

                .AppendLine("<head>")
                .AppendLine("<title>")
                .AppendLine("Welcome")
                .AppendLine("</title>")
                .AppendLine("</head>")

                .AppendLine("<body>")
                .AppendLine("<H1>Welcome</H1>")
                .AppendLine("<p>You have reached the default application page.</p>")
                .AppendLine("<H4>Additional Resources:</H4>")
                .AppendLine("<ul>")
                .AppendLine("<li><a href=\"http://katanaproject.codeplex.com/\">Katana Project</a>")
                .AppendLine("<li><a href=\"http://www.owin.org/\">owin.org</a>")
                .AppendLine("</ul>")
                .AppendLine("</body>")
                .AppendLine("</html>");
                return(response.WriteAsync(builder.ToString()));
            }
            return(_next(environment));
        }
Exemplo n.º 3
0
        public Task ProcesseRequest(OwinRequest request)
        {
            var resource = _getResource();
            var response = new OwinResponse(request.Environment)
            {
                ContentType   = _attribute.ContentType,
                ContentLength = resource.Length
            };

            return(response.WriteAsync(resource));
        }
Exemplo n.º 4
0
        private static Task InvokeHandler(OwinResponse res, Func <OwinRequest, object> routeHandler, OwinRequest req)
        {
            var result         = routeHandler(req);
            var flaskyResponse = result as IResponse;

            if (flaskyResponse != null)
            {
                return(flaskyResponse.Write(res));
            }
            res.ContentType = "text/plain";
            return(res.WriteAsync(result.ToString()));
        }
Exemplo n.º 5
0
        public Task ProcessRequest(OwinRequest request)
        {
            byte[] resource = GetResource();

            var response = new OwinResponse(request.Environment)
            {
                ContentType   = data.ContentType,
                ContentLength = resource.Length
            };

            return(response.WriteAsync(resource));
        }
        public Task Invoke(IDictionary <string, object> environment)
        {
            OwinRequest  request  = new OwinRequest(environment);
            OwinResponse response = new OwinResponse(environment);

            response.ContentType = "text/plain";

            string responseText = request.GetHeader("breadcrumbs") + "\r\n"
                                  + "PathBase: " + request.PathBase + "\r\n"
                                  + "Path: " + request.Path + "\r\n";

            return(response.WriteAsync(responseText));
        }
Exemplo n.º 7
0
        public Task Invoke(IDictionary <string, object> environment)
        {
            var request = new OwinRequest(environment);

            if (string.IsNullOrEmpty(_options.Path) || string.Equals(request.Path, _options.Path, StringComparison.OrdinalIgnoreCase))
            {
                // TODO: Make it pretty
                OwinResponse response = new OwinResponse(environment);
                response.ContentType = "text/plain";
                return(response.WriteAsync("Welcome to Katana"));
            }
            return(_next(environment));
        }
Exemplo n.º 8
0
        public AppFunc DefaultApplication(AppFunc next)
        {
            return(env =>
            {
                if (env.Get <string>("OwinDefaultMiddleWare") != "OwinDefaultMiddleWare" || env.Get <string>("Alpha") != "Alpha" || env.Get <string>("Beta") != "Beta")
                {
                    throw new Exception("Test failed to find appropriate custom value added by middleware");
                }

                OwinResponse response = new OwinResponse(env);
                return response.WriteAsync("SUCCESS");
            });
        }
Exemplo n.º 9
0
        public Task Invoke(IDictionary <string, object> env)
        {
            var body = Encoding.UTF8.GetBytes("404");

            var response = new OwinResponse(env)
            {
                ReasonPhrase  = "",
                StatusCode    = 404,
                ContentType   = "text/plain;charset=utf-8",
                ContentLength = body.Length
            };

            return(response.WriteAsync(body));
        }
Exemplo n.º 10
0
            public async Task Invoke(IDictionary <string, object> env)
            {
                OwinRequest request = new OwinRequest(env);

                if (request.Path == "/raw")
                {
                    OwinResponse response = new OwinResponse(request);
                    response.ContentType = "text/plain";
                    await response.WriteAsync("Hello from OWIN!");
                }
                else
                {
                    await _nextFunc(env);
                }
            }
Exemplo n.º 11
0
        private static async Task SendFileToResponse(OwinResponse response, CrossAppDomainResponseFile file)
        {
            if (response.CanSendFile)
            {
                await response.SendFileAsync(file.Path, file.Length, file.Offset, CancellationToken.None);

                return;
            }

            var buffer = new byte[file.Length - file.Offset];

            using (var stream = File.OpenRead(file.Path)) {
                stream.Seek(file.Offset, SeekOrigin.Begin);
                await stream.ReadAsync(buffer, 0, (int)file.Length);
            }
            await response.WriteAsync(buffer);
        }
Exemplo n.º 12
0
        public Task ProcesseRequest(OwinRequest request)
        {
            var parameters = _getHttpRequestParams(request);
            var res        = _action(parameters);
            var json       = JsonConvert.SerializeObject(res);
            var jsonBytes  = Encoding.UTF8.GetBytes(json);
            var response   = new OwinResponse(request.Environment)
            {
                Headers =
                {
                    { "Cache-Control", new [] { "no-store", "no-cache" } },
                    { "Pragma",        new [] { "no-cache" } }
                },
                ContentType   = "application/json;charset=utf-8",
                ContentLength = jsonBytes.Length
            };

            return(response.WriteAsync(jsonBytes));
        }
Exemplo n.º 13
0
        public Task Invoke(IDictionary <string, object> env)
        {
            try {
                var request = new OwinRequest(env);
                var path    = request.Path.Value.TrimEnd(new[] { '/' });

                if (path.Equals("/contracts", StringComparison.OrdinalIgnoreCase))
                {
                    var responce = new OwinResponse(env);
                    return(responce.WriteAsync("My email: [email protected], contact phone: +1234567890"));
                }
            }
            catch (Exception ex) {
                var tcs = new TaskCompletionSource <object>();
                tcs.SetException(ex);
                return(tcs.Task);
            }
            return(this._next(env));
        }
        public void WritesWork()
        {
            var body         = new MemoryStream(4);
            var expectedBody = new byte[] { 65, 66, 67, 68 };
            var cts          = new CancellationTokenSource();
            var env          = new Dictionary <string, object>(StringComparer.Ordinal)
            {
                { "owin.CallCancelled", cts.Token },
                { "owin.ResponseBody", body },
            };

            var res = new OwinResponse(env);

            res.Write("AB");
            res.WriteAsync("CD").Wait();

            body.GetBuffer().ShouldBe(expectedBody);
            res.CallCancelled.ShouldBe(cts.Token);
        }
Exemplo n.º 15
0
        public async Task UpdateWithResponseData(IDictionary <string, object> environment, CrossAppDomainResponseData responseData)
        {
            var response = new OwinResponse(environment);

            response.StatusCode   = responseData.StatusCode;
            response.ReasonPhrase = responseData.StatusDescription;

            foreach (var pair in responseData.Headers)
            {
                response.Headers.Add(pair.Key, new[] { pair.Value });
            }

            foreach (var data in responseData.Body)
            {
                await response.WriteAsync(data);
            }

            foreach (var file in responseData.Files)
            {
                await SendFileToResponse(response, file);
            }
        }
        public async Task Invoke(IDictionary<string, object> env)
        {
            var req = new OwinRequest(env);
            string file;
            if (!_router.TryGet(req.Path, out file))
            {
                await _next(env);
            }

            var resp = new OwinResponse(req)
            {
                ContentType = "text/html"
            };

            if (!File.Exists(file))
            {
                resp.StatusCode = 404;
                await resp.WriteAsync("File not found");
            }
            using (var fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                await fs.CopyToAsync(resp.Body);
            }
        }
Exemplo n.º 17
0
 // Invoked once per request.
 public Task Invoke(OwinRequest request, OwinResponse response)
 {
     response.ContentType = "text/plain";
     return(response.WriteAsync("Hello World"));
 }
Exemplo n.º 18
0
        public void Configuration(IAppBuilder app)
        {
            app.UseDispatcher(dispatcher =>
            {
                // list all the things:
                dispatcher.Get("/things", (environment, next) =>
                {
                    var response = new OwinResponse(environment)
                    {
                        StatusCode  = 200,
                        ContentType = "text/plain"
                    };

                    response.Write("# All the things:");
                    response.Write(Environment.NewLine);
                    response.Write(Environment.NewLine);

                    foreach (var thing in _things.Values)
                    {
                        response.Write(String.Concat("- Thing #", thing.Id, ": ", thing.Name));
                        response.Write(Environment.NewLine);
                    }

                    return(Task.FromResult((object)null));
                });

                // create a new thing:
                dispatcher.Post("/things", async(environment, next) =>
                {
                    var request = new OwinRequest(environment);
                    var form    = await request.ReadFormAsync();

                    var response = new OwinResponse(environment);

                    var thingName = form["name"];

                    if (thingName == null)
                    {
                        response.StatusCode = 400;
                        await response.WriteAsync("The thing to POST is missing a name.");
                        return;
                    }

                    _things.Add(++_lastThingId, new Thing
                    {
                        Id   = _lastThingId,
                        Name = thingName
                    });
                    var uri = String.Concat("/things/", _lastThingId);

                    response.StatusCode          = 201;
                    response.Headers["Location"] = uri;
                    response.ContentType         = "text/plain";
                    await response.WriteAsync(uri);
                });

                // list all the things:
                dispatcher.Get("/things/{id}", (environment, @params, next) =>
                {
                    var response = new OwinResponse(environment);

                    int id;
                    if (!int.TryParse(@params.id, out id))
                    {
                        response.StatusCode = 404;
                        return(response.WriteAsync("Not found."));
                    }

                    if (!_things.ContainsKey(id))
                    {
                        response.StatusCode = 404;
                        return(response.WriteAsync("Not found."));
                    }

                    var thing = _things[id];

                    response.StatusCode  = 200;
                    response.ContentType = "text/plain";

                    return(response.WriteAsync(String.Concat("Thing #", thing.Id, " is ", thing.Name, ".")));
                });
            });
        }
Exemplo n.º 19
0
 public Task Write(OwinResponse response)
 {
     response.ContentType = "application/json";
     return(response.WriteAsync(_objectToWrite.ToJson()));
 }
Exemplo n.º 20
0
        public Task Invoke(IDictionary <string, object> environment)
        {
            var response = new OwinResponse(environment);

            return(response.WriteAsync(this._breadcrumb));
        }
Exemplo n.º 21
0
 public static Task RespondMethodNotAllowed(this OwinResponse response)
 {
     response.StatusCode   = 405;
     response.ReasonPhrase = "Method Not Allowed";
     return(response.WriteAsync("Request method not allowed."));
 }
Exemplo n.º 22
0
 public static Task RespondNotFound(this OwinResponse response)
 {
     response.StatusCode   = 404;
     response.ReasonPhrase = "Not Found";
     return(response.WriteAsync("Not Found"));
 }
Exemplo n.º 23
0
 public static Task RespondString(this OwinResponse response, string content, string contentType = "text/plain")
 {
     response.SetHeader("Content-Type", contentType + ";charset=utf-8");
     return(response.WriteAsync(content));
 }
        public void WritesWork()
        {
            var body = new MemoryStream(4);
            var expectedBody = new byte[] { 65, 66, 67, 68 };
            var cts = new CancellationTokenSource();
            var env = new Dictionary<string, object>(StringComparer.Ordinal)
                {
                    { "owin.CallCancelled", cts.Token },
                    { "owin.ResponseBody", body },
                };

            var res = new OwinResponse(env);
            res.Write("AB");
            res.WriteAsync("CD").Wait();

            body.GetBuffer().ShouldBe(expectedBody);
            res.CallCancelled.ShouldBe(cts.Token);
        }