private async Task WriteOutputAsync(HttpContext context, IAsset asset, IAssetResponse cachedResponse, string cacheKey, WebOptimizerOptions options) { context.Response.ContentType = asset.ContentType; foreach (string name in cachedResponse.Headers.Keys) { context.Response.Headers[name] = cachedResponse.Headers[name]; } if (!string.IsNullOrEmpty(cacheKey)) { if (options.EnableCaching == true) { context.Response.Headers[HeaderNames.CacheControl] = $"max-age=31536000"; // 1 year } context.Response.Headers[HeaderNames.ETag] = $"\"{cacheKey}\""; if (IsConditionalGet(context, cacheKey)) { context.Response.StatusCode = 304; return; } } if (cachedResponse?.Body?.Length > 0) { await context.Response.Body.WriteAsync(cachedResponse.Body, 0, cachedResponse.Body.Length); } }
/// <summary> /// Gets the file content asynchronous. /// </summary> /// <exception cref="FileNotFoundException">File or bundle doesn't exist</exception> protected async Task <string> GetFileContentAsync(string route) { if (Pipeline.TryGetAssetFromRoute(route, out IAsset asset)) { IAssetResponse response = await _builder.BuildAsync(asset, ViewContext.HttpContext, Options); return(response.Body.AsString()); } string cacheKey = "_WO_" + route; if (Cache.TryGetValue(cacheKey, out string content)) { return(content); } string cleanRoute = route.TrimStart('~'); string file = HostingEnvironment.WebRootFileProvider.GetFileInfo(cleanRoute).PhysicalPath; if (File.Exists(file)) { using (StreamReader reader = File.OpenText(file)) { content = await reader.ReadToEndAsync(); AddToCache(cacheKey, content, HostingEnvironment.WebRootFileProvider, cleanRoute); return(content); } } throw new FileNotFoundException("File or bundle doesn't exist", route); }
private async Task HandleAssetAsync(HttpContext context, IAsset asset, WebOptimizerOptions options) { IAssetResponse response = await _assetBuilder.BuildAsync(asset, context, options); if (response == null) { await _next(context); return; } await WriteOutputAsync(context, asset, response, response.CacheKey, options); }