IIS Enable Dynamic Compression for JSON via Powershell
In my effort to make my application as fast as possible, I needed to compress the JSON being returned by my application to speed up the download time. It is quite easy to turn on compression for IIS. You 100% should do it for static content (HTML, CSS, JavaScript) and generally should for dynamic content as well. Those two are simple changes in the UI or via Desired State Configuration (DSC). One thing that some people don't know is that it won't compress your JSON by default and you have to do some extra steps to get that to work. You can follow the steps at https://stackoverflow.com/a/17331627/14275 to do it through the UI if that's what you want to do.
I'm trying to automate everything so I don't miss a step, so I wanted a way to create a script to do this automatically. Here is a Powershell script that will check if JSON is set to be compressed, and it is isn't, add it to the list.
if(((Get-WebConfigurationProperty -pspath 'MACHINE/WEBROOT/APPHOST' -filter "system.webServer/httpCompression" -Name "dynamicTypes").Collection | Where-Object { $_.mimeType -eq 'application/json' }).Length -eq 1){
Write-Host "'application/json' already configured"
} else {
Add-WebConfigurationProperty -pspath 'MACHINE/WEBROOT/APPHOST' -filter "system.webServer/httpCompression/dynamicTypes" -name "." -value @{mimeType='application/json';enabled='True'}
Write-Host "'application/json' added successfully"
}
if(((Get-WebConfigurationProperty -pspath 'MACHINE/WEBROOT/APPHOST' -filter "system.webServer/httpCompression" -Name "dynamicTypes").Collection | Where-Object { $_.mimeType -eq 'application/json; charset=utf-8' }).Length -eq 1){
Write-Host "'application/json; charset=utf-8' already configured"
} else {
Add-WebConfigurationProperty -pspath 'MACHINE/WEBROOT/APPHOST' -filter "system.webServer/httpCompression/dynamicTypes" -name "." -value @{mimeType='application/json; charset=utf-8';enabled='True'}
Write-Host "'application/json; charset=utf-8' added successfully"
}