Пример #1
0
        public StaticFileContext(HttpContext context, StaticFileOptions options, ILogger logger, IFileProvider fileProvider, string contentType, PathString subPath)
        {
            _context         = context;
            _options         = options;
            _request         = context.Request;
            _response        = context.Response;
            _logger          = logger;
            _fileProvider    = fileProvider;
            _method          = _request.Method;
            _contentType     = contentType;
            _fileInfo        = null;
            _etag            = null;
            _requestHeaders  = null;
            _responseHeaders = null;
            _range           = null;

            _length                 = 0;
            _subPath                = subPath;
            _lastModified           = new DateTimeOffset();
            _ifMatchState           = PreconditionState.Unspecified;
            _ifNoneMatchState       = PreconditionState.Unspecified;
            _ifModifiedSinceState   = PreconditionState.Unspecified;
            _ifUnmodifiedSinceState = PreconditionState.Unspecified;

            if (HttpMethods.IsGet(_method))
            {
                _requestType = RequestType.IsGet;
            }
            else if (HttpMethods.IsHead(_method))
            {
                _requestType = RequestType.IsHead;
            }
            else
            {
                _requestType = RequestType.Unspecified;
            }
        }
Пример #2
0
        /// Sets the Cache-Control header for static content, conditionally allowing the browser to use the content
        /// without revalidation.
        private void SetCacheControlHeaderForStaticContent(IHostingEnvironment env, HttpContext context)
        {
            var headers = new ResponseHeaders(context.Response.Headers);

            // Don't set Cache-Control for HTML files (e.g. /tzdb/). The browser can figure out when to revalidate
            // (Which it can do easily, since we send an ETag with all static content responses).
            // Also don't set cache control for build.txt and commit.txt, which are diagnostic files designed
            // to show "the version being served" and should never be cached.
            if (headers.ContentType.IsSubsetOf(TextHtml) ||
                context.Request.Path.Value == "/build.txt" ||
                context.Request.Path.Value == "/commit.txt")
            {
                return;
            }

            // Otherwise if the request was made with a file version query parameter (?v=..., as sent by
            // asp-append-version=true), then we can always use the response 'indefinitely', even in development mode.
            if (context.Request.Query.ContainsKey("v"))
            {
                headers.CacheControl = new CacheControlHeaderValue
                {
                    Public = true,
                    MaxAge = TimeSpan.FromDays(365)
                };
                return;
            }

            // Otherwise, the remaining content (/favicon.ico, /fonts/, /robots.txt, /styles/docfx.js etc) should be
            // good to use for a while without revalidation. When running in the Development environment, we'll use a
            // much shorter time, since we might be iterating on it (in particular, this also covers the unminified
            // JS/CSS).
            headers.CacheControl = new CacheControlHeaderValue
            {
                Public = true,
                MaxAge = env.IsDevelopment() ? TimeSpan.FromMinutes(2) : TimeSpan.FromDays(1)
            };
        }
        async Task <Stream> IHttpUpgradeFeature.UpgradeAsync()
        {
            if (!((IHttpUpgradeFeature)this).IsUpgradableRequest)
            {
                throw new InvalidOperationException(CoreStrings.CannotUpgradeNonUpgradableRequest);
            }

            if (IsUpgraded)
            {
                throw new InvalidOperationException(CoreStrings.UpgradeCannotBeCalledMultipleTimes);
            }

            if (!ServiceContext.ConnectionManager.UpgradedConnectionCount.TryLockOne())
            {
                throw new InvalidOperationException(CoreStrings.UpgradedConnectionLimitReached);
            }

            IsUpgraded = true;

            ConnectionFeatures.Get <IDecrementConcurrentConnectionCountFeature>()?.ReleaseConnection();

            StatusCode   = StatusCodes.Status101SwitchingProtocols;
            ReasonPhrase = "Switching Protocols";
            ResponseHeaders["Connection"] = "Upgrade";
            if (!ResponseHeaders.ContainsKey("Upgrade"))
            {
                StringValues values;
                if (RequestHeaders.TryGetValue("Upgrade", out values))
                {
                    ResponseHeaders["Upgrade"] = values;
                }
            }

            await FlushAsync(default(CancellationToken));

            return(_streams.Upgrade());
        }
        partial void ExtractFailureContent(
            string?content,
            ResponseHeaders responseHeaders,
            ref string?message,
            ref string?errorCode,
            ref IDictionary <string, string>?additionalInfo)
#pragma warning restore CA1801 // Remove unused parameter
#pragma warning restore CA1822 // Member can be static
        {
            if (!string.IsNullOrEmpty(content))
            {
                try
                {
                    using JsonDocument doc = JsonDocument.Parse(content);
                    if (doc.RootElement.TryGetProperty("error", out JsonElement errorElement))
                    {
                        foreach (JsonProperty property in errorElement.EnumerateObject())
                        {
                            switch (property.Name)
                            {
                            case "code":
                                errorCode = property.Value.GetString();
                                break;

                            case "message":
                                message = property.Value.GetString();
                                break;
                            }
                        }
                    }
                }
                catch (JsonException)
                {
                }
            }
        }
        /// <summary>
        /// Adds the given header object to Response
        /// </summary>
        /// <param name="newHeader"></param>
        public void AddHeader(HttpHeader newHeader)
        {
            if (NonUniqueResponseHeaders.ContainsKey(newHeader.Name))
            {
                NonUniqueResponseHeaders[newHeader.Name].Add(newHeader);
                return;
            }

            if (ResponseHeaders.ContainsKey(newHeader.Name))
            {
                var existing = ResponseHeaders[newHeader.Name];
                ResponseHeaders.Remove(newHeader.Name);

                NonUniqueResponseHeaders.Add(newHeader.Name,
                                             new List <HttpHeader>()
                {
                    existing, newHeader
                });
            }
            else
            {
                ResponseHeaders.Add(newHeader.Name, newHeader);
            }
        }
Пример #6
0
        private async Task <HttpResponseMessage> Forward()
        {
            HttpResponseMessage response;

            using (var client = new HttpClient {
                Timeout = TimeSpan.FromSeconds(10)
            }) {
                var requestMethod = ParseHttpMethod(HttpMethod);
                var message       = new HttpRequestMessage(requestMethod, Destination);

                foreach (var header in Headers)
                {
                    message.Headers.Add(header.Name, header.Value);
                }

                message.Headers.Host = new Uri(Destination).Host;

                if (requestMethod != System.Net.Http.HttpMethod.Get)
                {
                    message.Content = new ByteArrayContent(Encoding.UTF8.GetBytes(Body));
                }

                response = await client.SendAsync(message);
            }

            ResponseHeaders.Clear();
            foreach (var header in response.Headers)
            {
                string value = string.Join(",", header.Value);
                ResponseHeaders.Add(new Header(header.Key, value));
            }

            ResponseBody = await response.Content.ReadAsStringAsync();

            return(response);
        }
Пример #7
0
        private void WriteBeginResponseHeaders()
        {
            if (HasStarted)
            {
                return;
            }

            HasStarted = true;
            
            if (_isHttp2)
            {
                throw new NotImplementedException();
            }
            else
            {
                _outputFormatter.Write(_http11Bytes);
                var status = ReasonPhrases.ToStatusBytes(StatusCode);
                _outputFormatter.Write(status);

                _autoChunk = !HasContentLength && !HasTransferEncoding && KeepAlive;

                ResponseHeaders.CopyTo(_autoChunk, _outputFormatter);
            }
        }
 public void SetHeader(ResponseHeaders header, string value)
 {
     this.SetHeader(header.GetDescription(), value);
 }
Пример #9
0
 public void SetHeader(ResponseHeaders header, string value)
 {
     SetHeaderByKey(header, value);
 }
 public ContentActionResultWithCorsWithoutCaching(HttpRequest request, object model, string corsSettings)
     : base(request, model)
 {
     ResponseHeaders.Add(new KeyValuePair <string, string>("Access-Control-Allow-Origin", corsSettings));
     ResponseHeaders.Add(new KeyValuePair <string, string>("Cache-Control", "private, max-age=0, no-cache"));
 }
Пример #11
0
 public void SetHeader(ResponseHeaders header, string value)
 {
     base.SetHeader(header, value);
 }
Пример #12
0
 public Response()
 {
     Headers = new ResponseHeaders(new HeaderDictionary());
 }
 public ContentActionResultWithoutCaching(HttpRequest request, object model) : base(request, model)
 {
     ResponseHeaders.Add(new KeyValuePair <string, string>("Cache-Control", "private, max-age=0, no-cache"));
 }
Пример #14
0
 public static void Import(this HttpResponse resp, ResponseHeaders headers)
 {
     throw new NotImplementedException();
 }
Пример #15
0
 IResponseBuilder IMessageBuilder <IResponseBuilder> .WithHeader(string key, params string[] values)
 {
     ResponseHeaders.Add(key, values);
     return(this);
 }
 protected void SetResponseHeaders(WebHeaderCollection headers)
 {
     responseHeaders = new ResponseHeaders(headers);
 }
Пример #17
0
        private void AcceptClientThread(IAsyncResult result)
        {
            TcpClient client = _listener.EndAcceptTcpClient(result);
            _proccessed_connection.Set();

            DebugUtilities.WriteInfo("Processing Connection from " + client.Client.RemoteEndPoint.ToString() + "!");
            NetworkStream stream = client.GetStream();

            DebugUtilities.WriteSpecial("Reading Stream");
            string request = "";
            byte[] buffer = new byte[512];
            int i = 0;
            do
            {

                i = stream.Read(buffer, 0, buffer.Length); //add the next set of data into the buffer..
                DebugUtilities.WriteSpecial("Read chunk from the stream");
               request += Encoding.UTF8.GetString(buffer, 0, i); //append it to the overall request
            }
            while (stream.DataAvailable); //and repeat :)

            DebugUtilities.WriteInfo("Got request, totalling " + request.Length + " characters");
            string[] split = request.Split(new string[] { "\r\n\r\n" }, StringSplitOptions.RemoveEmptyEntries);

            string hostname = "unknown";
            try
            {
                EndPoint endpoint = client.Client.RemoteEndPoint;
                DebugUtilities.WriteDebug("ip: " + endpoint.ToString());
                string ip = (endpoint.ToString().Split(':'))[0];
                IPHostEntry host = Dns.GetHostEntry(IPAddress.Parse(ip));
                hostname = host.HostName;
                DebugUtilities.WriteDebug("ENDPOINT HOSTNAME: " + hostname);
            }
            catch
            {
                DebugUtilities.WriteWarning("Could not parse ip address to get the hostname (ipv6?) -  hostname is set as 'unknown'");
            }

            RequestHeaders x = new RequestHeaders(split[0], hostname);

            string body = "";

            bool foundExpectContinue = false;
            foreach(HeaderLine line in x.HeaderLines)
            {
                if(line.ToString() == "Expect: 100-continue")
                {
                    foundExpectContinue = true;
                    DebugUtilities.WriteSpecial("Found 100 continue!");
                }
            }

            if(foundExpectContinue)
            {
                try
                {
                    ResponseHeaders continue_response = new ResponseHeaders(100, "Continue");
                    byte[] byte_continue_response = System.Text.Encoding.UTF8.GetBytes(continue_response.ToString());

                    //send the 100 continue message and then go back to the above.
                    DebugUtilities.WriteSpecial("Writing 100 continue response");
                    stream.Write(byte_continue_response,0,byte_continue_response.Length);
                    DebugUtilities.WriteSpecial("Finished writing - " + byte_continue_response.Length + " bytes total sent");

                    request = "";
                    buffer = new byte[512];
                    i = 0;
                    if (stream.DataAvailable) DebugUtilities.WriteSpecial("DATA AVALIABLE!!");
                    else DebugUtilities.WriteWarning("NO DATA AVALIABLE? Hurr");

                    do
                    {
                        i = stream.Read(buffer, 0, buffer.Length); //add the next set of data into the buffer..
                        DebugUtilities.WriteSpecial("Read continued chunk from the stream");
                        request += Encoding.UTF8.GetString(buffer, 0, i); //append it to the overall request
                    }
                    while (stream.DataAvailable); //and repeat :)

                    DebugUtilities.WriteInfo("Got continued request, totalling " + request.Length + " characters");

                    DebugUtilities.WriteDebug("Heres what I got: " + request);
                    body = request;
                }
                catch
                {
                    DebugUtilities.WriteError("An error occured while trying to talk to the client (100 expectation response)");
                }
            }
            else if (split.Length > 1) body = split[1];

            string to_return = Program.DoProcessing(x, body);
            to_return = "<restbot>" + to_return + "</restbot>";
            DebugUtilities.WriteDebug("What I should return to the client: " + to_return);

            ResponseHeaders response_headers = new ResponseHeaders(200, "OK");
            string response = response_headers.ToString() + to_return;

            try
            {
                byte[] the_buffer = System.Text.Encoding.UTF8.GetBytes(response);
                response = ""; //unset for the hell of it
                stream.Write(the_buffer, 0, the_buffer.Length);
            }
            catch
            {
                DebugUtilities.WriteError("Could not write to the network stream!");
                //see below
            }

            try
            {
                stream.Close();
                client.Close();
            }
            catch
            {
                DebugUtilities.WriteError("An error occured while closing the stream");
                //ignore, sometimes the connection was closed by the client
            }
        }
Пример #18
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory, IWebHostEnvironment hostingEnvironment)
        {
            // Log hosting environment
            {
                ILogger logger = loggerFactory.CreateLogger("Startup");
                logger.LogInformation("Using content root: {0}", hostingEnvironment.ContentRootPath);
                logger.LogInformation("Using web root: {0}", hostingEnvironment.WebRootPath);
            }

            // Startup checks
            if (!app.RunStartupChecks())
            {
                return;
            }

            // HTTP pipeline configuration
            app.UseHttps();
            app.UseMiddleware <SiteUrlDetectionService.Middleware>();

            app.UseRouting();
            app.UseAuthentication();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();

                app.UseWhen(
                    ctx => ctx.Request.Path.StartsWithSegments("/build") ||
                    ctx.Request.Path.StartsWithSegments("/sw-es5.js") ||
                    ctx.Request.Path.StartsWithSegments("/sw-es2017.js") ||
                    ctx.Request.Path.StartsWithSegments("/__webpack_hmr"),
                    spaApp => {
                    spaApp.UseSpa(spa => {
                        const int port = 8080;

                        Process.Start(new ProcessStartInfo {
                            FileName         = "node.exe",
                            Arguments        = $"dev-server.js --port={port}",
                            WorkingDirectory = hostingEnvironment.ContentRootPath,
                            UseShellExecute  = true,
                            WindowStyle      = ProcessWindowStyle.Minimized
                        });

                        spa.UseProxyToSpaDevelopmentServer($"http://localhost:{port}/");
                    });
                }
                    );
            }
            else
            {
                app.UseExceptionHandler("/");
            }

            app.UseResponseCompression();

            app.UseSimpleUrlRemap("/browserconfig.xml", "/images/tiles/manifest-microsoft.xml");
            app.UseSimpleUrlRemap("/sw-es5.js", "/build/es5/sw-es5.js");
            app.UseSimpleUrlRemap("/sw-es2017.js", "/build/es2017/sw-es2017.js");

            app.AddWildcardPatternRewrite("/build");

            app.UseStaticFiles(new StaticFileOptions {
                ContentTypeProvider = new FileExtensionContentTypeProvider {
                    // TODO: Remove when https://github.com/aspnet/AspNetCore/issues/2442 is done
                    Mappings = { [".webmanifest"] = "application/manifest+json" }
                },
                OnPrepareResponse = context => {
                    // Enable aggressive caching behavior - but be sure that requests from service workers must be properly addressed
                    const int expireTimeInDays = 7 * 4;

                    ResponseHeaders headers = context.Context.Response.GetTypedHeaders();
                    headers.Expires         = DateTimeOffset.Now.AddDays(expireTimeInDays);
                    headers.CacheControl    = new CacheControlHeaderValue {
                        MaxAge         = TimeSpan.FromDays(expireTimeInDays),
                        MustRevalidate = true,
                        Public         = true,
                        MaxStale       = true,
                        MaxStaleLimit  = TimeSpan.FromSeconds(5)
                    };
                }
            });

            // Let's encrypt support
            app.UseRouter(r => {
                r.MapGet(".well-known/acme-challenge/{id}", async(request, response, routeData) => {
                    string id = routeData.Values["id"] as string;
                    if (id != Path.GetFileName(id))
                    {
                        return; // Prevent injection attack
                    }

                    string file = Path.Combine(env.WebRootPath, ".well-known", "acme-challenge", id);
                    await response.SendFileAsync(file);
                });
            });

            // Hangfire
            app.UseHangfireServer();
            app.UseHangfireDashboard("/_internal/jobs", new DashboardOptions {
                AppPath = "/",
                DisplayStorageConnectionString = false,
                Authorization = new IDashboardAuthorizationFilter[] {
                    new DiagnosticsHangfireDashboardAuthorizationFilter(),
                }
            });

            // SPA bootstrapper
            app.UseEndpoints(endpoints => {
                // SignalR hub
                endpoints.MapHub <AppOwnerHub>("/extern/connect/app-owner");

                // MVC api controllers
                endpoints.MapControllers();

                // If we still reached this at this point the ko-template was not found:
                // Trigger an failure instead of sending the app bootstrapper which causes all kinds of havoc.
                endpoints.MapFailedRoute("ko-templates/{*.}");
                endpoints.MapFailedRoute("build/{*.}");

                // Any non-matched web api calls should fail as well
                endpoints.MapFailedRoute("api/{*.}");

                // We only match one controller since we will want
                // all requests to go to the controller which renders
                // the initial view / SPA bootstrapper.
                endpoints.MapFallbackToController("{*.}", "Index", "Home");
            });

            // Configure recurring jobs
            AppInsightsJobFilterAttribute.Register(app.ApplicationServices.GetService <TelemetryClient>());
            RecurringJob.AddOrUpdate <MonthlyDigestInvocationJob>(x => x.Execute(), Cron.Daily(10));
        }
Пример #19
0
        /// <summary>
        /// Configure the application.
        /// <see href="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/startup#the-configure-method"/>
        /// </summary>
        /// <param name="appBuilder">The application builder</param>
        /// <param name="env">Hosting environment</param>
        public void Configure(IApplicationBuilder appBuilder, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                appBuilder.UseExceptionHandler("/error-local-development");
            }
            else
            {
                appBuilder.UseExceptionHandler("/error");
            }

            Console.WriteLine($"// Program.cs // Configure // Trying to use static files.");

            appBuilder.UseStaticFiles(new StaticFileOptions
            {
                OnPrepareResponse = context =>
                {
                    ResponseHeaders headers = context.Context.Response.GetTypedHeaders();
                    headers.CacheControl    = new CacheControlHeaderValue
                    {
                        Public = true,
                        MaxAge = TimeSpan.FromMinutes(60),
                    };
                },
            });

            Console.WriteLine($"// Program.cs // Configure // Successfully using static files.");

            const string swaggerRoutePrefix = "designer/swagger";

            appBuilder.UseSwagger(c =>
            {
                c.RouteTemplate = swaggerRoutePrefix + "/{documentName}/swagger.json";
            });
            appBuilder.UseSwaggerUI(c =>
            {
                c.RoutePrefix = swaggerRoutePrefix;
                c.SwaggerEndpoint($"/{swaggerRoutePrefix}/v1/swagger.json", "Altinn Designer API V1");
            });

            appBuilder.UseRouting();

            // appBuilder.UseHsts();
            // appBuilder.UseHttpsRedirection();
            appBuilder.UseAuthentication();
            appBuilder.UseAuthorization();

            appBuilder.UseResponseCompression();
            appBuilder.UseRequestLocalization();

            Console.WriteLine($"// Program.cs // Configure // Attempting to add endpoints.");

            appBuilder.UseEndpoints(endpoints =>
            {
                // ------------------------- DEV ----------------------------- //
                endpoints.MapControllerRoute(
                    name: "orgRoute",
                    pattern: "designer/{org}/{controller}/{action=Index}/",
                    defaults: new { controller = "Config" },
                    constraints: new
                {
                    controller = "Config|Datamodels",
                });

                endpoints.MapControllerRoute(
                    name: "serviceDevelopmentRoute",
                    pattern: "designer/{org}/{app}",
                    defaults: new { controller = "ServiceDevelopment", action = "index" },
                    constraints: new
                {
                    app = "^[a-z]+[a-zA-Z0-9-]+[a-zA-Z0-9]$",
                });

                endpoints.MapControllerRoute(
                    name: "designerApiRoute",
                    pattern: "designerapi/{controller}/{action=Index}/{id?}",
                    defaults: new { controller = "Repository" },
                    constraints: new
                {
                    controller = @"(Repository|Language|User)",
                });
                endpoints.MapControllerRoute(
                    name: "serviceRoute",
                    pattern: "designer/{org}/{app}/{controller}/{action=Index}/{id?}",
                    defaults: new { controller = "Service" },
                    constraints: new
                {
                    controller = @"(Codelist|Config|Service|RuntimeAPI|ManualTesting|Model|Rules|ServiceMetadata|Text|UI|UIEditor|ServiceDevelopment)",
                    app        = "^[a-z]+[a-zA-Z0-9-]+[a-zA-Z0-9]$",
                    id         = "[a-zA-Z0-9_\\-\\.]{1,30}",
                });

                endpoints.MapControllerRoute(
                    name: "applicationMetadataApiRoute",
                    pattern: "designer/api/v1/{org}/{app}",
                    defaults: new { controller = "ApplicationMetadata", action = "ApplicationMetadata" });

                endpoints.MapControllerRoute(
                    name: "reposRoute",
                    pattern: "{controller}/{action}/",
                    defaults: new { controller = "RedirectController" });

                // -------------------------- DEFAULT ------------------------- //
                endpoints.MapControllerRoute(
                    name: "defaultRoute2",
                    pattern: "{controller}/{action=StartPage}/{id?}",
                    defaults: new { controller = "Home" });

                endpoints.MapControllerRoute(
                    name: "defaultRoute",
                    pattern: "{action=StartPage}/{id?}",
                    defaults: new { controller = "Home" });

                // ---------------------- MONITORING -------------------------- //
                endpoints.MapHealthChecks("/health");
            });

            Console.WriteLine($"// Program.cs // Configure // Successfully added endpoints.");
        }
 public override void WriteHeaders(Microsoft.AspNetCore.Http.HttpContext context, ResponseHeaders headers)
 {
     headers.SetFileHeaders(this.fileName, encoder.DefaultMimeType, this.inline);
 }
Пример #21
0
 public override void WriteHeaders(Microsoft.AspNetCore.Http.HttpContext context, ResponseHeaders headers)
 {
     base.WriteHeaders(context, headers);
     headers.ContentType = new Microsoft.Net.Http.Headers.MediaTypeHeaderValue("application/json");
 }
Пример #22
0
        protected override ResponseError?ExtractFailureContent(
            string?content,
            ResponseHeaders responseHeaders,
            ref IDictionary <string, string>?additionalInfo
            )
        {
            additionalInfo = new Dictionary <string, string>();

            if (content != null && responseHeaders.ContentType != null)
            {
                // XML body
                if (responseHeaders.ContentType.Contains(Constants.ContentTypeApplicationXml))
                {
                    XDocument xml       = XDocument.Parse(content);
                    var       errorCode = xml.Root.Element(Constants.ErrorCode).Value;
                    var       message   = xml.Root.Element(Constants.ErrorMessage).Value;

                    foreach (XElement element in xml.Root.Elements())
                    {
                        switch (element.Name.LocalName)
                        {
                        case Constants.ErrorCode:
                        case Constants.ErrorMessage:
                            continue;

                        default:
                            additionalInfo[element.Name.LocalName] = element.Value;
                            break;
                        }
                    }

                    return(new ResponseError(errorCode, message));
                }

                // Json body
                else if (responseHeaders.ContentType.Contains(Constants.ContentTypeApplicationJson))
                {
                    JsonDocument json  = JsonDocument.Parse(content);
                    JsonElement  error = json.RootElement.GetProperty(Constants.ErrorPropertyKey);

                    IDictionary <string, string>?details = default;
                    if (error.TryGetProperty(Constants.DetailPropertyKey, out JsonElement detail))
                    {
                        details = new Dictionary <string, string>();
                        foreach (JsonProperty property in detail.EnumerateObject())
                        {
                            details[property.Name] = property.Value.GetString();
                        }
                    }

                    var message   = error.GetProperty(Constants.MessagePropertyKey).GetString();
                    var errorCode = error.GetProperty(Constants.CodePropertyKey).GetString();
                    additionalInfo = details;
                    return(new ResponseError(errorCode, message));
                }
            }
            // No response body.
            else
            {
                // The other headers will appear in the "Headers" section of the Exception message.
                if (responseHeaders.TryGetValue(Constants.HeaderNames.ErrorCode, out string?value))
                {
                    return(new ResponseError(value, null));
                }
            }

            return(null);
        }
        private async Task ExecuteRequests(Hl7.Fhir.Model.Bundle responseBundle, Hl7.Fhir.Model.Bundle.HTTPVerb httpVerb)
        {
            foreach (RouteContext request in _requests[httpVerb])
            {
                var entryComponent = new Hl7.Fhir.Model.Bundle.EntryComponent();

                if (request.Handler != null)
                {
                    HttpContext httpContext = request.HttpContext;

                    IFhirRequestContext originalFhirRequestContext = _fhirRequestContextAccessor.FhirRequestContext;

                    request.RouteData.Values.TryGetValue(KnownActionParameterNames.ResourceType, out object resourceType);
                    var newFhirRequestContext = new FhirRequestContext(
                        httpContext.Request.Method,
                        httpContext.Request.GetDisplayUrl(),
                        originalFhirRequestContext.BaseUri.OriginalString,
                        originalFhirRequestContext.CorrelationId,
                        httpContext.Request.Headers,
                        httpContext.Response.Headers,
                        resourceType?.ToString())
                    {
                        Principal = originalFhirRequestContext.Principal,
                    };
                    _fhirRequestContextAccessor.FhirRequestContext = newFhirRequestContext;

                    _bundleHttpContextAccessor.HttpContext = httpContext;

                    await request.Handler.Invoke(httpContext);

                    httpContext.Response.Body.Seek(0, SeekOrigin.Begin);
                    string bodyContent = new StreamReader(httpContext.Response.Body).ReadToEnd();

                    ResponseHeaders responseHeaders = httpContext.Response.GetTypedHeaders();
                    entryComponent.Response = new Hl7.Fhir.Model.Bundle.ResponseComponent
                    {
                        Status       = httpContext.Response.StatusCode.ToString(),
                        Location     = responseHeaders.Location?.OriginalString,
                        Etag         = responseHeaders.ETag?.ToString(),
                        LastModified = responseHeaders.LastModified,
                    };

                    if (!string.IsNullOrWhiteSpace(bodyContent))
                    {
                        var entryComponentResource = _fhirJsonParser.Parse <Resource>(bodyContent);

                        if (entryComponentResource.ResourceType == ResourceType.OperationOutcome)
                        {
                            entryComponent.Response.Outcome = entryComponentResource;

                            if (responseBundle.Type == Hl7.Fhir.Model.Bundle.BundleType.TransactionResponse)
                            {
                                ThrowTransactionException(httpContext, (OperationOutcome)entryComponentResource);
                            }
                        }
                        else
                        {
                            entryComponent.Resource = entryComponentResource;
                        }
                    }
                    else
                    {
                        if (httpContext.Response.StatusCode == (int)HttpStatusCode.Forbidden)
                        {
                            entryComponent.Response.Outcome = CreateOperationOutcome(
                                OperationOutcome.IssueSeverity.Error,
                                OperationOutcome.IssueType.Forbidden,
                                Api.Resources.Forbidden);
                        }
                    }
                }
                else
                {
                    entryComponent.Response = new Hl7.Fhir.Model.Bundle.ResponseComponent
                    {
                        Status  = ((int)HttpStatusCode.NotFound).ToString(),
                        Outcome = CreateOperationOutcome(
                            OperationOutcome.IssueSeverity.Error,
                            OperationOutcome.IssueType.NotFound,
                            string.Format(Api.Resources.BundleNotFound, $"{request.HttpContext.Request.Path}{request.HttpContext.Request.QueryString}")),
                    };
                }

                responseBundle.Entry.Add(entryComponent);
            }
        }
Пример #24
0
        public void MergeFrom(HttpStreamedTraceSegment other)
        {
            if (other == null)
            {
                return;
            }
            if (other.TraceId != 0UL)
            {
                TraceId = other.TraceId;
            }
            switch (other.MessagePieceCase)
            {
            case MessagePieceOneofCase.RequestHeaders:
                if (RequestHeaders == null)
                {
                    RequestHeaders = new global::Envoy.Api.V2.Core.HeaderMap();
                }
                RequestHeaders.MergeFrom(other.RequestHeaders);
                break;

            case MessagePieceOneofCase.RequestBodyChunk:
                if (RequestBodyChunk == null)
                {
                    RequestBodyChunk = new global::Envoy.Data.Tap.V2Alpha.Body();
                }
                RequestBodyChunk.MergeFrom(other.RequestBodyChunk);
                break;

            case MessagePieceOneofCase.RequestTrailers:
                if (RequestTrailers == null)
                {
                    RequestTrailers = new global::Envoy.Api.V2.Core.HeaderMap();
                }
                RequestTrailers.MergeFrom(other.RequestTrailers);
                break;

            case MessagePieceOneofCase.ResponseHeaders:
                if (ResponseHeaders == null)
                {
                    ResponseHeaders = new global::Envoy.Api.V2.Core.HeaderMap();
                }
                ResponseHeaders.MergeFrom(other.ResponseHeaders);
                break;

            case MessagePieceOneofCase.ResponseBodyChunk:
                if (ResponseBodyChunk == null)
                {
                    ResponseBodyChunk = new global::Envoy.Data.Tap.V2Alpha.Body();
                }
                ResponseBodyChunk.MergeFrom(other.ResponseBodyChunk);
                break;

            case MessagePieceOneofCase.ResponseTrailers:
                if (ResponseTrailers == null)
                {
                    ResponseTrailers = new global::Envoy.Api.V2.Core.HeaderMap();
                }
                ResponseTrailers.MergeFrom(other.ResponseTrailers);
                break;
            }

            _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
        }
Пример #25
0
 protected void SetResponseHeaders()
 {
     responseHeaders = new ResponseHeaders(Response);
 }
Пример #26
0
 public string GetHeader(ResponseHeaders header)
 {
     return(base.GetHeader(header));
 }
Пример #27
0
        /// <summary>
        /// 通过枚举获取应答头
        /// </summary>
        /// <param name="header"></param>
        /// <returns></returns>
        public string GetHeader(ResponseHeaders header)
        {
            var fieldName = ResponseHeadersHelper.headerMap[header];

            return(GetHeader(fieldName));
        }
        public async Task Invoke(HttpContext context)
        {
            context.Response.ContentType = "text/html; charset=utf-8";
            string   _path = context.Request.Path.ToString().Replace(LoggerSettings.LogRequestPath, "");
            FileInfo file  = new FileInfo(Path.Combine(this._fileDirectory, _path.TrimStart(new char[]
            {
                '\\',
                '/'
            })));

            context.Response.Headers.Add("Accept-Ranges", "bytes");
            EntityTagHeaderValue _tag = null;
            bool exists = file.Exists;

            if (exists)
            {
                long value = file.LastAccessTime.ToUniversalTime().ToFileTime() ^ file.Length;
                _tag = EntityTagHeaderValue.Parse("\"" + Convert.ToString(value, 16) + "\"");
                bool flag = context.Request.Headers.Keys.Contains("If-None-Match");
                if (flag)
                {
                    string tag   = context.Request.Headers["If-None-Match"].ToString();
                    bool   flag2 = tag == _tag.Tag;
                    if (flag2)
                    {
                        context.Response.StatusCode = 304;
                        await Task.CompletedTask;
                        return;
                    }
                    tag = null;
                }
                if (_tag != null)
                {
                    ResponseHeaders _responseHeaders = context.Response.GetTypedHeaders();
                    _responseHeaders.LastModified = new DateTimeOffset?(file.LastAccessTime);
                    _responseHeaders.ETag         = _tag;
                    _responseHeaders.CacheControl = new CacheControlHeaderValue
                    {
                        MaxAge = new TimeSpan?(TimeSpan.FromHours(2.0))
                    };
                    _responseHeaders = null;
                }
                string fileContent;
                using (FileStream _stream = file.OpenRead())
                {
                    using (StreamReader _reader = new StreamReader(_stream))
                    {
                        fileContent = _reader.ReadToEnd();
                    }
                }
                StringBuilder html       = new StringBuilder(MarkdownFileMiddleware.markdownHtmlContent);
                PathString    pathString = context.Request.Path;
                string        text       = "/";
                string[]      array      = pathString.Value.Split(new char[]
                {
                    '/'
                }, StringSplitOptions.RemoveEmptyEntries);
                StringBuilder stringBuilder = new StringBuilder("<a href='" + LoggerSettings.SettingsPath + "'>Settings</a>&nbsp;&nbsp;");
                foreach (string text2 in array)
                {
                    text = string.Format("{0}{1}/", text, text2);
                    if (text.TrimEnd(new char[]
                    {
                        '/'
                    }) == context.Request.Path)
                    {
                        stringBuilder.AppendFormat("<a href='javascript:;'>{0}</a>", MarkdownFileMiddleware._htmlEncoder.Encode(text2));
                    }
                    else
                    {
                        stringBuilder.AppendFormat("<a href=\"{0}\">{1}/</a>", MarkdownFileMiddleware._htmlEncoder.Encode(text), MarkdownFileMiddleware._htmlEncoder.Encode(text2));
                    }
                }
                html.Replace("{{content}}", "|时间|消息|请求|错误|跟踪|\r\n|--|--|--|--|--|\r\n" + fileContent).Replace("{{title}}", string.Join("/", array.Take(array.Length - 1))).Replace("{{link}}", stringBuilder.ToString());
                context.Response.StatusCode = 200;
                await context.Response.WriteAsync(html.ToString(), Encoding.UTF8, default(CancellationToken));

                fileContent   = null;
                html          = null;
                pathString    = default(PathString);
                text          = null;
                array         = null;
                stringBuilder = null;
            }
        }
Пример #29
0
        /// <summary>
        /// 通过枚举设置应答头
        /// </summary>
        /// <param name="header"></param>
        /// <param name="value"></param>
        public void SetHeader(ResponseHeaders header, string value)
        {
            var fieldName = ResponseHeadersHelper.headerMap[header];

            SetHeader(fieldName, value);
        }
Пример #30
0
 public string GetHeader(ResponseHeaders header)
 {
     return(GetHeaderByKey(header));
 }
Пример #31
0
        public MemoryResponse()
        {
            Headers = new ResponseHeaders();

        }
 List <string> IServiceConfiguration.GetResponseHeaders() => ResponseHeaders.Get();
Пример #33
0
 public void Setup()
 {
     _headerDictionary = new Dictionary <string, string[]>(StringComparer.OrdinalIgnoreCase); //Per OWIN 1.0 spec.
     _responseHeaders  = new ResponseHeaders(_headerDictionary);
 }