How does ASP.NET vNext handle Caching, Compression & MimeMap in config.json? - asp.net

In previous versions all of these settings could be added and tweaked in the Web.Config file using something like the code below:
<staticContent>
<mimeMap fileExtension=".webp" mimeType="image/webp" />
<!-- Caching -->
<clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="96:00:00" />
</staticContent>
<httpCompression directory="%SystemDrive%\inetpub\temp\IIS Temporary Compressed Files">
<scheme name="gzip" dll="%Windir%\system32\inetsrv\gzip.dll" />
<dynamicTypes>
<add mimeType="text/*" enabled="true" />
<add mimeType="message/*" enabled="true" />
<add mimeType="application/javascript" enabled="true" />
<add mimeType="*/*" enabled="false" />
</dynamicTypes>
<staticTypes>
<add mimeType="text/*" enabled="true" />
<add mimeType="message/*" enabled="true" />
<add mimeType="application/javascript" enabled="true" />
<add mimeType="*/*" enabled="false" />
</staticTypes>
</httpCompression>
<urlCompression doStaticCompression="true" doDynamicCompression="true"/>
However, with the Web.Config no longer being around in ASP.NET vNext, how do you adjust settings like this? I have searched the net and the ASP.NET Github repo, but not come across anything - any ideas?

As "agua from mars" states in the comments, if you're using IIS you can use IIS's static file handling, in which case you can use the <system.webServer> section in a web.config file and that will work as it always did.
If you're using ASP.NET 5's StaticFileMiddleware then it has its own MIME mappings that come as part of the FileExtensionContentTypeProvider implementation. The StaticFileMiddleware has a StaticFileOptions that you can use to configure it when you initialize it in Startup.cs. In that options class you can set the content type provider. You can instantiate the default content type provider and then just tweak the mappings dictionary, or you can write an entire mapping from scratch (not recommended).
ASP.NET Core - mime mappings:
If the extended set of file types you are providing for the entire site are not going to change, you can configure a single instance of the ContentTypeProvider class, and then leverage DI to use it when serving static files, like so:
public void ConfigureServices(IServiceCollection services)
{
...
services.AddInstance<IContentTypeProvider>(
new FileExtensionConentTypeProvider(
new Dictionary<string, string>(
// Start with the base mappings
new FileExtensionContentTypeProvider().Mappings,
// Extend the base dictionary with your custom mappings
StringComparer.OrdinalIgnoreCase) {
{ ".nmf", "application/octet-stream" }
{ ".pexe", "application/x-pnal" },
{ ".mem", "application/octet-stream" },
{ ".res", "application/octet-stream" }
}
)
);
...
}
public void Configure(
IApplicationBuilder app,
IContentTypeProvider contentTypeProvider)
{
...
app.UseStaticFiles(new StaticFileOptions() {
ContentTypeProvider = contentTypeProvider
...
});
...
}

Related

Can QuartzServer NET decrypts connection string in config file?

I'm using Quartz.Server.exe 2.X as job executor.
I'm using Quartz.Server.exe.config to configure quartz.
<quartz >
<add key="quartz.scheduler.instanceName" value="AlyCE_LROScheduler" />
<add key="quartz.jobStore.type" value="Quartz.Impl.AdoJobStore.JobStoreTX, Quartz" />
<add key="quartz.jobStore.useProperties" value="true" />
<add key="quartz.jobStore.driverDelegateType" value="Quartz.Impl.AdoJobStore.SqlServerDelegate, Quartz" />
<add key="quartz.jobStore.tablePrefix" value="QUARTZ_" />
<add key="quartz.jobStore.dataSource" value="defaultDS" />
<add key="quartz.jobStore.lockHandler.type" value="Quartz.Impl.AdoJobStore.UpdateLockRowSemaphore, Quartz" />
<add key="quartz.dataSource.defaultDS.provider" value="SqlServer-20" />
<add key="quartz.dataSource.defaultDS.connectionString" value="my connection string to encrypt/decrypt" />
</quartz>
All works fine. Now I'd like to encrypt the connection string for security reason.
Is there a way to let Quartz.Server.exe to understand encrypted connection string?
Thanks
I solved.
I removed the connection string quartz property and I added the connectionProvider.type property, that let me to override the standard Quartz.Impl.AdoJobStore.Common.DbProvider.
So I am able to decrypt my connection string.
So my config looks like this:
<quartz >
<!-- thread pool info -->
<add key="quartz.threadPool.type" value="Quartz.Simpl.SimpleThreadPool, Quartz" />
<!-- job store info -->
<add key="quartz.jobStore.type" value="Quartz.Impl.AdoJobStore.JobStoreTX, Quartz" />
<add key="quartz.jobStore.useProperties" value="true" />
<add key="quartz.jobStore.driverDelegateType" value="Quartz.Impl.AdoJobStore.SqlServerDelegate, Quartz" />
<add key="quartz.jobStore.tablePrefix" value="QUARTZ_" />
<add key="quartz.jobStore.dataSource" value="defaultDS" />
<add key="quartz.jobStore.lockHandler.type" value="Quartz.Impl.AdoJobStore.UpdateLockRowSemaphore, Quartz" />
<add key="quartz.dataSource.defaultDS.connectionProvider.type" value="MyDll.MyDbProvider, MyDll" />
</quartz>
<connectionStrings>
<add key="myConnString" connectionString="crypted"/>
</connectionStrings>
Then I create new class library project where I created this class:
public class MyDbProvider : DbProvider
{
public MyDbProvider() : base("SqlServer-20", MyHelper.GetConnectionString()) { }
}
public static class MyHelper
{
public static string GetConnectionString()
{
//here i decrypt my connection string from app.config file
}
}
MyDll.dll must be in the same directory of Quartz.Server.exe .
Hope this can help someone!

PageSpeed google Enable Compression often changing

I'm working on an ASP.NET webforms and I put this code in my web.config :
<httpCompression directory="%SystemDrive%\inetpub\temp\IIS Temporary Compressed Files">
<scheme name="gzip" dll="%Windir%\system32\inetsrv\gzip.dll"/>
<dynamicTypes>
<add mimeType="text/*" enabled="true"/>
<add mimeType="message/*" enabled="true"/>
<add mimeType="application/javascript" enabled="true"/>
<add mimeType="application/x-javascript" enabled="true"/>
<add mimeType="*/*" enabled="false"/>
</dynamicTypes>
<staticTypes>
<add mimeType="text/*" enabled="true"/>
<add mimeType="message/*" enabled="true"/>
<add mimeType="application/javascript" enabled="true"/>
<add mimeType="application/x-javascript" enabled="true"/>
<add mimeType="*/*" enabled="false"/>
</staticTypes>
</httpCompression>
<urlCompression doStaticCompression="true" doDynamicCompression="true"/>
Sometimes Google Page Speed Insights and PageSpeed extension on Chrome don't say the same message about enable compression. Sometimes there are about 10 files so it's high importance, sometimes it's just 4 files, so medium importance... Sometimes Mobile version shows 10 files while computer version shows 4. It seems to be random. For instance. I analyse at 11:00 it's not the same at 11:30 and not the same at 13:00... Can change everytime without data or code changes.
Can someone explain this strange thing ?
By the way, I don't know why among the 4 remaining files, there are still a css file and a js file not "enabled" since other css and js files are not in the list anymore.
I also would like to remove the WebResource.axd?d=...&t=... from the 4 remaining files on some pages. That's why I added a mimeType x-javascript. But it doesn't seem to work.
Thanks.
here what you should do:
1. Enable dynamic compression in IIS7 enable compression
2. Enable page compression by using this code:
public static bool IsGZipSupported()
{
string AcceptEncoding = HttpContext.Current.Request.Headers[«Accept-Encoding»];
if (!string.IsNullOrEmpty(AcceptEncoding) &&
(AcceptEncoding.Contains(«gzip») || AcceptEncoding.Contains(«deflate»)))
return true;
return false;
}
public static void GZipEncodePage()
{
if (IsGZipSupported())
{
HttpResponse Response = HttpContext.Current.Response;
string AcceptEncoding = HttpContext.Current.Request.Headers[«Accept-Encoding»];
if (AcceptEncoding.Contains(«gzip»))
{
Response.Filter = new System.IO.Compression.GZipStream(Response.Filter,
System.IO.Compression.CompressionMode.Compress);
Response.AppendHeader(«Content-Encoding», «gzip»);
}
else
{
Response.Filter = new System.IO.Compression.DeflateStream(Response.Filter,
System.IO.Compression.CompressionMode.Compress);
Response.AppendHeader(«Content-Encoding», «deflate»);
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
HtmlUtil.GZipEncodePage();
}
Enable static content enable static content

IIS7 GZIP Compression - httpCompression section

I trying to configure httpCompression on IIS7. By googling, I found that it can be made using httpCompression section in config. The problem, that I can't make it work from web.config.
When I make the configuration in applicationHost.config everything works as needed, but I want to be able to make this configuration per application and not globally.
I changed section definition in applicationHost.config to <section name="httpCompression" overrideModeDefault="Allow" /> and moved httpCompression section to web.config:
<httpCompression directory="%SystemDrive%\inetpub\temp\IIS Temporary Compressed Files">
<scheme name="gzip" dll="%Windir%\system32\inetsrv\gzip.dll" />
<staticTypes>
<add mimeType="text/*" enabled="true" />
<add mimeType="message/*" enabled="true" />
<add mimeType="application/x-javascript" enabled="true" />
<add mimeType="application/atom+xml" enabled="true" />
<add mimeType="application/xaml+xml" enabled="true" />
<add mimeType="*/*" enabled="false" />
</staticTypes>
<dynamicTypes>
<add mimeType="text/*" enabled="true" />
<add mimeType="message/*" enabled="true" />
<add mimeType="application/x-javascript" enabled="true" />
<add mimeType="application/json" enabled="true" />
<add mimeType="application/json; charset=utf-8" enabled="true" />
<add mimeType="*/*" enabled="false" />
</dynamicTypes>
</httpCompression>
What am I missing? It looks like IIS not reads compression configurations from web.config at all.
After each change, I make application pool recycle, so it not a problem.
as per this ServerFault answer: https://serverfault.com/a/125156/117212 - you can't change httpCompression in web.config, it needs to be done in applicationHost.config file. Here is the code I use in my Azure web role to modify applicationHost.config file and add mime types for compression:
using (var serverManager = new ServerManager())
{
var config = serverManager.GetApplicationHostConfiguration();
var httpCompressionSection = config.GetSection("system.webServer/httpCompression");
var dynamicTypesCollection = httpCompressionSection.GetCollection("dynamicTypes");
Action<string> fnCheckAndAddIfMissing = mimeType =>
{
if (dynamicTypesCollection.Any(x =>
{
var v = x.GetAttributeValue("mimeType");
if (v != null && v.ToString() == mimeType)
{
return true;
}
return false;
}) == false)
{
ConfigurationElement addElement = dynamicTypesCollection.CreateElement("add");
addElement["mimeType"] = mimeType;
addElement["enabled"] = true;
dynamicTypesCollection.AddAt(0, addElement);
}
};
fnCheckAndAddIfMissing("application/json");
fnCheckAndAddIfMissing("application/json; charset=utf-8");
serverManager.CommitChanges();
}
ServerManager comes from Microsoft.Web.Administration package in NuGet.
You should check the whole config file hierarchy.
If you removed the section from applicationHost you may be inheriting from machine.config or a web.config of a parent directory.

Adding tracelistener to web.config

I want to use below code with a website. Which config sections I should add to web.config to log the output into a file or windows eventlog ?
using System.Diagnostics;
// Singleton in real code
Class Logger
{
// In constructor: Trace.AutoFlush = false;
public void Log(message)
{
String formattedLog = formatLog(message);
Trace.TraceInformation(formattedLog);
Trace.Flush();
}
}
You should use system.diagnostics section.
Here's example from MSDN for text file:
<configuration>
<system.diagnostics>
<trace autoflush="false" indentsize="4">
<listeners>
<add name="myListener"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="TextWriterOutput.log" />
<remove name="Default" />
</listeners>
</trace>
</system.diagnostics>
</configuration>
This is for system events log: http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlogtracelistener.aspx

How do I compress a Json result from ASP.NET MVC with IIS 7.5

I'm having difficulty making IIS 7 correctly compress a Json result from ASP.NET MVC. I've enabled static and dynamic compression in IIS. I can verify with Fiddler that normal text/html and similar records are compressed. Viewing the request, the accept-encoding gzip header is present. The response has the mimetype "application/json", but is not compressed.
I've identified that the issue appears to relate to the MimeType. When I include mimeType="*/*", I can see that the response is correctly gzipped. How can I get IIS to compress WITHOUT using a wildcard mimeType? I assume that this issue has something to do with the way that ASP.NET MVC generates content type headers.
The CPU usage is well below the dynamic throttling threshold. When I examine the trace logs from IIS, I can see that it fails to compress due to not finding a matching mime type.
<httpCompression directory="%SystemDrive%\inetpub\temp\IIS Temporary Compressed Files" noCompressionForProxies="false">
<scheme name="gzip" dll="%Windir%\system32\inetsrv\gzip.dll" />
<dynamicTypes>
<add mimeType="text/*" enabled="true" />
<add mimeType="message/*" enabled="true" />
<add mimeType="application/x-javascript" enabled="true" />
<add mimeType="application/json" enabled="true" />
</dynamicTypes>
<staticTypes>
<add mimeType="text/*" enabled="true" />
<add mimeType="message/*" enabled="true" />
<add mimeType="application/x-javascript" enabled="true" />
<add mimeType="application/atom+xml" enabled="true" />
<add mimeType="application/xaml+xml" enabled="true" />
<add mimeType="application/json" enabled="true" />
</staticTypes>
</httpCompression>
Make sure your %WinDir%\System32\inetsrv\config\applicationHost.config contains these:
<system.webServer>
<urlCompression doDynamicCompression="true" />
<httpCompression>
<dynamicTypes>
<add mimeType="application/json" enabled="true" />
<add mimeType="application/json; charset=utf-8" enabled="true" />
</dynamicTypes>
</httpCompression>
</system.webServer>
From the link of #AtanasKorchev.
As #simon_weaver said in the comments, you might be editing the wrong file with a 32 bit editor on a 64 bit Windows, use notepad.exe to make sure this file is indeed modified.
I have successfully used the approach highlighted here.
Use this guide
None of these answers worked for me. I did take note of the application/json; charset=utf-8 mime-type though.
I recommend this approach
Create CompressAttribute class, and set target action.
The ActionFilterAttribute approach updated for ASP.NET 4.x and Includes Brotli.NET package.
using System;
using System.IO.Compression;
using Brotli;
using System.Web;
using System.Web.Mvc;
public class CompressFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
HttpRequestBase request = filterContext.HttpContext.Request;
string acceptEncoding = request.Headers["Accept-Encoding"];
if (string.IsNullOrEmpty(acceptEncoding)) return;
acceptEncoding = acceptEncoding.ToUpperInvariant();
HttpResponseBase response = filterContext.HttpContext.Response;
if (acceptEncoding.Contains("BR"))
{
response.AppendHeader("Content-encoding", "br");
response.Filter = new BrotliStream(response.Filter, CompressionMode.Compress);
}
else if (acceptEncoding.Contains("GZIP"))
{
response.AppendHeader("Content-encoding", "gzip");
response.Filter = new GZipStream(response.Filter, CompressionMode.Compress);
}
else if (acceptEncoding.Contains("DEFLATE"))
{
response.AppendHeader("Content-encoding", "deflate");
response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress);
}
}
}

Resources