Compare commits
11 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6b00d8e194 | ||
|
|
772a11a710 | ||
|
|
be2158f38b | ||
|
|
efffeafae4 | ||
|
|
86382a36c6 | ||
|
|
9c87801818 | ||
|
|
bac99a3817 | ||
|
|
31df13215b | ||
|
|
a2f9c5e5d5 | ||
|
|
2bab2c3d1d | ||
|
|
fbcaa3ce4b |
@@ -1,7 +1,7 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio 14
|
||||
VisualStudioVersion = 14.0.25123.0
|
||||
VisualStudioVersion = 14.0.25420.1
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "CompressR.MVC", "src\CompressR.MVC\CompressR.MVC.shproj", "{13E4DCA3-5D4D-4796-B3CF-AD4620E2A2F1}"
|
||||
EndProject
|
||||
@@ -20,15 +20,20 @@ EndProject
|
||||
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{84E10868-C75C-4FDF-8AE1-465F1593A211}"
|
||||
ProjectSection(SolutionItems) = preProject
|
||||
appveyor.yml = appveyor.yml
|
||||
gulpfile.js = gulpfile.js
|
||||
EndProjectSection
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CompressR.WebApiUnitTests", "src\CompressR.WebApiUnitTests\CompressR.WebApiUnitTests.csproj", "{61D97564-ACF6-4396-AB96-2D29CDCC3814}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CompressR.Owin", "src\CompressR.Owin\CompressR.Owin.csproj", "{4B84A645-A7E3-446E-83B5-5F56D18B47DF}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CompressR.Owin.Sample", "src\CompressR.Owin.Sample\CompressR.Owin.Sample.csproj", "{C6DD2187-F71A-4DA3-99B0-47A8CCF10853}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SharedMSBuildProjectFiles) = preSolution
|
||||
src\CompressR.MVC\CompressR.MVC.projitems*{b8889368-e350-4b1e-82f5-ea537d6da6e9}*SharedItemsImports = 4
|
||||
src\CompressR.MVC\CompressR.MVC.projitems*{13e4dca3-5d4d-4796-b3cf-ad4620e2a2f1}*SharedItemsImports = 13
|
||||
src\CompressR.MVC\CompressR.MVC.projitems*{256f0ecd-0310-4de9-8334-31a3d3867925}*SharedItemsImports = 4
|
||||
src\CompressR.MVC\CompressR.MVC.projitems*{b8889368-e350-4b1e-82f5-ea537d6da6e9}*SharedItemsImports = 4
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
@@ -63,6 +68,14 @@ Global
|
||||
{61D97564-ACF6-4396-AB96-2D29CDCC3814}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{61D97564-ACF6-4396-AB96-2D29CDCC3814}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{61D97564-ACF6-4396-AB96-2D29CDCC3814}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{4B84A645-A7E3-446E-83B5-5F56D18B47DF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{4B84A645-A7E3-446E-83B5-5F56D18B47DF}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{4B84A645-A7E3-446E-83B5-5F56D18B47DF}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{4B84A645-A7E3-446E-83B5-5F56D18B47DF}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{C6DD2187-F71A-4DA3-99B0-47A8CCF10853}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{C6DD2187-F71A-4DA3-99B0-47A8CCF10853}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{C6DD2187-F71A-4DA3-99B0-47A8CCF10853}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{C6DD2187-F71A-4DA3-99B0-47A8CCF10853}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
|
||||
19
Readme.md
19
Readme.md
@@ -59,4 +59,23 @@ public class ValuesController : ApiController
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
## Owin
|
||||
|
||||
You can add gzip support through a middleware. Install the package: `Install-Package CompressR.Owin`. Then add `app.Use<GzipMiddleware>();` to your `Startup.cs`.
|
||||
|
||||
|
||||
```csharp
|
||||
|
||||
public void Configuration(IAppBuilder app)
|
||||
{
|
||||
app.Use<GzipMiddleware>();
|
||||
app.Run(context =>
|
||||
{
|
||||
context.Response.ContentType = "text/plain";
|
||||
return context.Response.WriteAsync("Hello World!");
|
||||
});
|
||||
}
|
||||
|
||||
```
|
||||
10
gulpfile.js
10
gulpfile.js
@@ -5,7 +5,7 @@ var download = require("gulp-download");
|
||||
var del = require('del');
|
||||
var assemblyInfo = require('gulp-dotnet-assembly-info');
|
||||
var xunit = xunit = require('gulp-xunit-runner');
|
||||
var version = '1.2.1';
|
||||
var version = '1.5.2';
|
||||
|
||||
gulp.task('clean', ()=>{
|
||||
return del(['src/**/obj/', 'src/**/bin/Release', 'nuget.exe', 'nupkgs'])
|
||||
@@ -24,6 +24,8 @@ gulp.task('patchAssemblyInfo', ()=>{
|
||||
.pipe(assemblyInfo({
|
||||
version: function(value) { return version; },
|
||||
fileVersion: function(value) { return version; },
|
||||
company: 'Tommy Parnell',
|
||||
copyright: 'Copyright © Tommy Parnell 2016'
|
||||
}))
|
||||
.pipe(gulp.dest('.'))
|
||||
});
|
||||
@@ -42,7 +44,11 @@ gulp.task('test', ['build'], function () {
|
||||
}));
|
||||
});
|
||||
gulp.task('pack', ['test'], ()=>{
|
||||
return gulp.src(['src/CompressR.MVC4/*.csproj', 'src/CompressR.MVC5/*.csproj', 'src/CompressR.WebApi/*.csproj', 'src/CompressR/*.csproj'], {read: false})
|
||||
return gulp.src(['src/CompressR.MVC4/*.csproj',
|
||||
'src/CompressR.MVC5/*.csproj',
|
||||
'src/CompressR.WebApi/*.csproj',
|
||||
'src/CompressR/*.csproj',
|
||||
'src/CompressR.Owin/*.csproj'], {read: false})
|
||||
.pipe(nuget.pack({
|
||||
build: false,
|
||||
symbols: true,
|
||||
|
||||
20
src/CompressR.MVC/BaseCompressAttribute.cs
Normal file
20
src/CompressR.MVC/BaseCompressAttribute.cs
Normal file
@@ -0,0 +1,20 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO.Compression;
|
||||
using System.Text;
|
||||
|
||||
namespace CompressR.MVC
|
||||
{
|
||||
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
|
||||
public abstract class BaseCompressAttribute : System.Web.Mvc.ActionFilterAttribute
|
||||
{
|
||||
protected bool RequireCompression { get; set; }
|
||||
|
||||
public CompressionLevel CompressionLevel { get; set; } = CompressionLevel.Optimal;
|
||||
|
||||
protected BaseCompressAttribute(bool requireCompression = false)
|
||||
{
|
||||
RequireCompression = requireCompression;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,18 +7,16 @@ using System.Web.Mvc;
|
||||
namespace CompressR.MVC
|
||||
{
|
||||
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
|
||||
public sealed class CompressAttribute : System.Web.Mvc.ActionFilterAttribute
|
||||
public sealed class CompressAttribute : BaseCompressAttribute
|
||||
{
|
||||
private bool RequireCompression { get; set; }
|
||||
|
||||
public CompressAttribute(bool requireCompression = false)
|
||||
: base(requireCompression)
|
||||
{
|
||||
RequireCompression = requireCompression;
|
||||
}
|
||||
|
||||
public override void OnActionExecuting(ActionExecutingContext filterContext)
|
||||
public override void OnResultExecuted(ResultExecutedContext filterContext)
|
||||
{
|
||||
CompressFactory.Compress(filterContext, RequireCompression);
|
||||
CompressFactory.Compress(filterContext, RequireCompression, CompressionLevel);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,21 +1,25 @@
|
||||
using CompressR.Exceptions;
|
||||
using System;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO.Compression;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using CompressR.Exceptions;
|
||||
|
||||
namespace CompressR.MVC
|
||||
{
|
||||
public static class CompressFactory
|
||||
{
|
||||
public static void Compress(string compression, System.Web.Mvc.ActionExecutingContext filterContext, bool requireCompression)
|
||||
public static void Compress(System.Web.Mvc.ResultExecutedContext filterContext, bool requireCompression, string compression, CompressionLevel compressLevel = CompressionLevel.Optimal)
|
||||
{
|
||||
if(filterContext.Exception != null && !filterContext.ExceptionHandled)
|
||||
{
|
||||
return;
|
||||
}
|
||||
var context = filterContext.RequestContext.HttpContext;
|
||||
var compressionAccepted = context.Request.Headers.Get(Constants.AcceptEncoding)?.Split(',').Trim().Any(a => string.Equals(a, compression, StringComparison.OrdinalIgnoreCase)) ?? false;
|
||||
if (!compressionAccepted)
|
||||
if(!compressionAccepted)
|
||||
{
|
||||
if (requireCompression)
|
||||
if(requireCompression)
|
||||
{
|
||||
throw new CompressRException("Compression required but client did not send accept header");
|
||||
}
|
||||
@@ -25,18 +29,20 @@ namespace CompressR.MVC
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
HandleCompression(compression, filterContext);
|
||||
HandleCompression(compression, filterContext, compressLevel);
|
||||
}
|
||||
|
||||
public static void Compress(System.Web.Mvc.ActionExecutingContext filterContext, bool requireCompression)
|
||||
public static void Compress(System.Web.Mvc.ResultExecutedContext filterContext, bool requireCompression, CompressionLevel compressLevel = CompressionLevel.Optimal)
|
||||
{
|
||||
if(filterContext.Exception != null && !filterContext.ExceptionHandled)
|
||||
{
|
||||
return;
|
||||
}
|
||||
var context = filterContext.RequestContext.HttpContext;
|
||||
var compressionAlgorithm = context.Request.Headers.Get(Constants.AcceptEncoding)?.Split(',').Trim().Intersect(Constants.Compressors, StringComparer.OrdinalIgnoreCase)?.FirstOrDefault();
|
||||
if (!string.IsNullOrWhiteSpace(compressionAlgorithm))
|
||||
if(!string.IsNullOrWhiteSpace(compressionAlgorithm))
|
||||
{
|
||||
HandleCompression(compressionAlgorithm, filterContext);
|
||||
HandleCompression(compressionAlgorithm, filterContext, compressLevel);
|
||||
}
|
||||
else if(requireCompression)
|
||||
{
|
||||
@@ -44,19 +50,24 @@ namespace CompressR.MVC
|
||||
}
|
||||
}
|
||||
|
||||
private static void HandleCompression(string compression, System.Web.Mvc.ActionExecutingContext filterContext)
|
||||
private static void HandleCompression(string compression, System.Web.Mvc.ResultExecutedContext filterContext, CompressionLevel compressLevel = CompressionLevel.Optimal)
|
||||
{
|
||||
var context = filterContext.RequestContext.HttpContext;
|
||||
switch (compression)
|
||||
HandleCompression(compression, filterContext.RequestContext.HttpContext, compressLevel);
|
||||
}
|
||||
|
||||
private static void HandleCompression(string compression, System.Web.HttpContextBase context, CompressionLevel compressLevel)
|
||||
{
|
||||
switch(compression)
|
||||
{
|
||||
case Constants.Gzip:
|
||||
context.Response.Filter = new GZipStream(context.Response.Filter, CompressionMode.Compress);
|
||||
context.Response.Filter = new GZipStream(context.Response.Filter, compressLevel);
|
||||
context.Response.AppendHeader(Constants.ContentEncoding, Constants.Gzip);
|
||||
context.Response.Cache.VaryByHeaders[Constants.AcceptEncoding] = true;
|
||||
break;
|
||||
|
||||
case Constants.Deflate:
|
||||
context.Response.Filter = new DeflateStream(context.Response.Filter, CompressionMode.Compress);
|
||||
context.Response.Filter = new DeflateStream(context.Response.Filter, compressLevel);
|
||||
context.Response.AppendHeader(Constants.ContentEncoding, Constants.Deflate);
|
||||
context.Response.Cache.VaryByHeaders[Constants.AcceptEncoding] = true;
|
||||
break;
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
<Import_RootNamespace>CompressR.MVC</Import_RootNamespace>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="$(MSBuildThisFileDirectory)BaseCompressAttribute.cs" />
|
||||
<Compile Include="$(MSBuildThisFileDirectory)CompressAttribute.cs" />
|
||||
<Compile Include="$(MSBuildThisFileDirectory)CompressFactory.cs" />
|
||||
<Compile Include="$(MSBuildThisFileDirectory)Constants.cs" />
|
||||
|
||||
@@ -1,8 +1,4 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
namespace CompressR.MVC
|
||||
namespace CompressR.MVC
|
||||
{
|
||||
public struct Constants
|
||||
{
|
||||
|
||||
@@ -1,17 +1,16 @@
|
||||
using System;
|
||||
using System.IO.Compression;
|
||||
using System.Linq;
|
||||
using System.Web.Mvc;
|
||||
|
||||
namespace CompressR.MVC
|
||||
{
|
||||
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
|
||||
public sealed class DeflateAttribute : System.Web.Mvc.ActionFilterAttribute
|
||||
public sealed class DeflateAttribute : BaseCompressAttribute
|
||||
{
|
||||
private bool RequireCompression { get; set; }
|
||||
|
||||
public DeflateAttribute(bool requireCompression = false)
|
||||
: base(requireCompression)
|
||||
{
|
||||
RequireCompression = requireCompression;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -19,9 +18,10 @@ namespace CompressR.MVC
|
||||
/// an action method.
|
||||
/// </summary>
|
||||
/// <param name="filterContext"></param>
|
||||
public override void OnActionExecuting(System.Web.Mvc.ActionExecutingContext filterContext)
|
||||
|
||||
public override void OnResultExecuted(ResultExecutedContext filterContext)
|
||||
{
|
||||
CompressFactory.Compress(Constants.Deflate, filterContext, RequireCompression);
|
||||
CompressFactory.Compress(filterContext, RequireCompression, CompressionLevel);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,4 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace CompressR.MVC
|
||||
{
|
||||
@@ -8,7 +6,7 @@ namespace CompressR.MVC
|
||||
{
|
||||
public static IEnumerable<string> Trim(this IEnumerable<string> arr)
|
||||
{
|
||||
foreach (var item in arr)
|
||||
foreach(var item in arr)
|
||||
{
|
||||
yield return item.Trim();
|
||||
}
|
||||
|
||||
@@ -1,27 +1,20 @@
|
||||
using System;
|
||||
using System.IO.Compression;
|
||||
using System.Linq;
|
||||
using System.Web.Mvc;
|
||||
|
||||
namespace CompressR.MVC
|
||||
{
|
||||
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
|
||||
public sealed class GzipAttribute : System.Web.Mvc.ActionFilterAttribute
|
||||
public sealed class GzipAttribute : BaseCompressAttribute
|
||||
{
|
||||
private bool RequireCompression { get; set; }
|
||||
|
||||
public GzipAttribute(bool requireCompression = false)
|
||||
: base(requireCompression)
|
||||
{
|
||||
RequireCompression = requireCompression;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Override to compress the content that is generated by
|
||||
/// an action method.
|
||||
/// </summary>
|
||||
/// <param name="filterContext"></param>
|
||||
public override void OnActionExecuting(System.Web.Mvc.ActionExecutingContext filterContext)
|
||||
public override void OnResultExecuted(ResultExecutedContext filterContext)
|
||||
{
|
||||
CompressFactory.Compress(Constants.Gzip, filterContext, RequireCompression);
|
||||
CompressFactory.Compress(filterContext, RequireCompression, CompressionLevel);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -14,7 +14,7 @@
|
||||
<copyright>Copyright 2016</copyright>
|
||||
<tags>Compression MVC</tags>
|
||||
<dependencies>
|
||||
<dependency id="Microsoft.AspNet.Mvc" version="(5.0.0, 6.0.0]" />
|
||||
<dependency id="Microsoft.AspNet.Mvc" version="[5.0.0, 6.0.0)" />
|
||||
</dependencies>
|
||||
</metadata>
|
||||
</package>
|
||||
@@ -33,8 +33,45 @@
|
||||
<WarningLevel>4</WarningLevel>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Reference Include="Castle.Core, Version=3.3.0.0, Culture=neutral, PublicKeyToken=407dd0808d44fbdc, processorArchitecture=MSIL">
|
||||
<HintPath>..\..\packages\Castle.Core.3.3.3\lib\net45\Castle.Core.dll</HintPath>
|
||||
<Private>True</Private>
|
||||
</Reference>
|
||||
<Reference Include="Microsoft.Web.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
|
||||
<HintPath>..\..\packages\Microsoft.Web.Infrastructure.1.0.0.0\lib\net40\Microsoft.Web.Infrastructure.dll</HintPath>
|
||||
<Private>True</Private>
|
||||
</Reference>
|
||||
<Reference Include="Moq, Version=4.5.10.0, Culture=neutral, PublicKeyToken=69f491c39445e920, processorArchitecture=MSIL">
|
||||
<HintPath>..\..\packages\Moq.4.5.10\lib\net45\Moq.dll</HintPath>
|
||||
<Private>True</Private>
|
||||
</Reference>
|
||||
<Reference Include="System" />
|
||||
<Reference Include="System.Core" />
|
||||
<Reference Include="System.Web" />
|
||||
<Reference Include="System.Web.Helpers, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
|
||||
<HintPath>..\..\packages\Microsoft.AspNet.WebPages.3.2.3\lib\net45\System.Web.Helpers.dll</HintPath>
|
||||
<Private>True</Private>
|
||||
</Reference>
|
||||
<Reference Include="System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
|
||||
<HintPath>..\..\packages\Microsoft.AspNet.Mvc.5.2.3\lib\net45\System.Web.Mvc.dll</HintPath>
|
||||
<Private>True</Private>
|
||||
</Reference>
|
||||
<Reference Include="System.Web.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
|
||||
<HintPath>..\..\packages\Microsoft.AspNet.Razor.3.2.3\lib\net45\System.Web.Razor.dll</HintPath>
|
||||
<Private>True</Private>
|
||||
</Reference>
|
||||
<Reference Include="System.Web.WebPages, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
|
||||
<HintPath>..\..\packages\Microsoft.AspNet.WebPages.3.2.3\lib\net45\System.Web.WebPages.dll</HintPath>
|
||||
<Private>True</Private>
|
||||
</Reference>
|
||||
<Reference Include="System.Web.WebPages.Deployment, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
|
||||
<HintPath>..\..\packages\Microsoft.AspNet.WebPages.3.2.3\lib\net45\System.Web.WebPages.Deployment.dll</HintPath>
|
||||
<Private>True</Private>
|
||||
</Reference>
|
||||
<Reference Include="System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
|
||||
<HintPath>..\..\packages\Microsoft.AspNet.WebPages.3.2.3\lib\net45\System.Web.WebPages.Razor.dll</HintPath>
|
||||
<Private>True</Private>
|
||||
</Reference>
|
||||
<Reference Include="System.Xml.Linq" />
|
||||
<Reference Include="System.Data.DataSetExtensions" />
|
||||
<Reference Include="Microsoft.CSharp" />
|
||||
@@ -60,6 +97,7 @@
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="Class1.cs" />
|
||||
<Compile Include="CompressionFactoryTests.cs" />
|
||||
<Compile Include="Properties\AssemblyInfo.cs" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
@@ -70,6 +108,10 @@
|
||||
<Project>{256f0ecd-0310-4de9-8334-31a3d3867925}</Project>
|
||||
<Name>CompressR.MVC5</Name>
|
||||
</ProjectReference>
|
||||
<ProjectReference Include="..\CompressR\CompressR.csproj">
|
||||
<Project>{c94378c3-4aa8-4f49-8720-77d14b62f72e}</Project>
|
||||
<Name>CompressR</Name>
|
||||
</ProjectReference>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
|
||||
|
||||
189
src/CompressR.MVCUnitTests/CompressionFactoryTests.cs
Normal file
189
src/CompressR.MVCUnitTests/CompressionFactoryTests.cs
Normal file
@@ -0,0 +1,189 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.IO.Compression;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Web;
|
||||
using System.Web.Mvc;
|
||||
using System.Web.Routing;
|
||||
using Moq;
|
||||
using Xunit;
|
||||
|
||||
namespace CompressR.MVCUnitTests
|
||||
{
|
||||
public class CompressionFactoryTests
|
||||
{
|
||||
[Fact]
|
||||
public void ShouldThrowWhenRequired()
|
||||
{
|
||||
var request = new Mock<HttpRequestBase>();
|
||||
request.Setup(a => a.Headers).Returns(new System.Collections.Specialized.NameValueCollection() { });
|
||||
var httpContext = new Moq.Mock<HttpContextBase>();
|
||||
httpContext.Setup(a => a.Request).Returns(request.Object);
|
||||
Assert.Throws(typeof(CompressR.Exceptions.CompressRException), () =>
|
||||
{
|
||||
CompressR.MVC.CompressFactory.Compress(new System.Web.Mvc.ResultExecutedContext()
|
||||
{
|
||||
HttpContext = httpContext.Object
|
||||
}, true);
|
||||
});
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ShouldNotThrowButAlsoNotCompressIfFalse()
|
||||
{
|
||||
var request = new Mock<HttpRequestBase>();
|
||||
request.Setup(a => a.Headers).Returns(new System.Collections.Specialized.NameValueCollection() { });
|
||||
var httpContext = new Moq.Mock<HttpContextBase>();
|
||||
httpContext.Setup(a => a.Request).Returns(request.Object);
|
||||
var response = new Mock<HttpResponseBase>();
|
||||
httpContext.Setup(a => a.Response).Returns(response.Object);
|
||||
var contextObject = httpContext.Object;
|
||||
CompressR.MVC.CompressFactory.Compress(new System.Web.Mvc.ResultExecutedContext()
|
||||
{
|
||||
HttpContext = contextObject
|
||||
}, false);
|
||||
Assert.Null(contextObject.Response.Filter);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ShouldGzipWhenRequested()
|
||||
{
|
||||
var request = new Mock<HttpRequestBase>();
|
||||
request.Setup(a => a.Headers).Returns(new System.Collections.Specialized.NameValueCollection() { ["Accept-Encoding"] = "gzip" });
|
||||
var requestContextBase = new Mock<HttpContextBase>();
|
||||
requestContextBase.Setup(a => a.Request).Returns(request.Object);
|
||||
var requestContext = new Mock<RequestContext>();
|
||||
requestContext.Setup(a => a.HttpContext).Returns(requestContextBase.Object);
|
||||
var cachePolicy = new Mock<HttpCachePolicyBase>();
|
||||
cachePolicy.Setup(a => a.VaryByHeaders).Returns(new HttpCacheVaryByHeaders());
|
||||
//var httpContext = new Moq.Mock<ActionExecutingContext>();
|
||||
var response = new Mock<HttpResponseBase>();
|
||||
response.Setup(a => a.Headers).Returns(new System.Collections.Specialized.NameValueCollection());
|
||||
response.SetupProperty(a => a.Filter, new MemoryStream(Encoding.UTF8.GetBytes("awesome")) { });
|
||||
response.Setup(a => a.Cache).Returns(cachePolicy.Object);
|
||||
var responseContext = new Mock<HttpContextBase>();
|
||||
responseContext.Setup(a => a.Response).Returns(response.Object);
|
||||
|
||||
requestContextBase.Setup(a => a.Response).Returns(response.Object);
|
||||
var httpContext = new ResultExecutedContext()
|
||||
{
|
||||
RequestContext = new System.Web.Routing.RequestContext()
|
||||
{
|
||||
HttpContext = requestContextBase.Object
|
||||
}
|
||||
};
|
||||
|
||||
//httpContext.Setup(a=>a.RequestContext.Filter).Returns(new MemoryStream(Encoding.UTF8.GetBytes("awesome")) { } );
|
||||
//var response = new Mock<HttpResponseBase>();
|
||||
//httpContext.Setup(a => a.Response).Returns(response.Object);
|
||||
//var contextObject = httpContext;
|
||||
CompressR.MVC.CompressFactory.Compress(httpContext, false);
|
||||
Assert.IsType<GZipStream>(httpContext.RequestContext.HttpContext.Response.Filter);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ShouldNotGzipWhenExceptionNotHandled()
|
||||
{
|
||||
var request = new Mock<HttpRequestBase>();
|
||||
request.Setup(a => a.Headers).Returns(new System.Collections.Specialized.NameValueCollection() { ["Accept-Encoding"] = "gzip" });
|
||||
var requestContextBase = new Mock<HttpContextBase>();
|
||||
requestContextBase.Setup(a => a.Request).Returns(request.Object);
|
||||
var requestContext = new Mock<RequestContext>();
|
||||
requestContext.Setup(a => a.HttpContext).Returns(requestContextBase.Object);
|
||||
var cachePolicy = new Mock<HttpCachePolicyBase>();
|
||||
cachePolicy.Setup(a => a.VaryByHeaders).Returns(new HttpCacheVaryByHeaders());
|
||||
//var httpContext = new Moq.Mock<ActionExecutingContext>();
|
||||
var response = new Mock<HttpResponseBase>();
|
||||
response.Setup(a => a.Headers).Returns(new System.Collections.Specialized.NameValueCollection());
|
||||
response.SetupProperty(a => a.Filter, new MemoryStream(Encoding.UTF8.GetBytes("awesome")) { });
|
||||
response.Setup(a => a.Cache).Returns(cachePolicy.Object);
|
||||
var responseContext = new Mock<HttpContextBase>();
|
||||
responseContext.Setup(a => a.Response).Returns(response.Object);
|
||||
|
||||
requestContextBase.Setup(a => a.Response).Returns(response.Object);
|
||||
var httpContext = new ResultExecutedContext()
|
||||
{
|
||||
RequestContext = new System.Web.Routing.RequestContext()
|
||||
{
|
||||
HttpContext = requestContextBase.Object
|
||||
},
|
||||
Exception = new Exception(),
|
||||
ExceptionHandled = false
|
||||
};
|
||||
CompressR.MVC.CompressFactory.Compress(httpContext, false);
|
||||
Assert.IsNotType<GZipStream>(httpContext.RequestContext.HttpContext.Response.Filter);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ShouldGzipWhenExceptionHandled()
|
||||
{
|
||||
var request = new Mock<HttpRequestBase>();
|
||||
request.Setup(a => a.Headers).Returns(new System.Collections.Specialized.NameValueCollection() { ["Accept-Encoding"] = "gzip" });
|
||||
var requestContextBase = new Mock<HttpContextBase>();
|
||||
requestContextBase.Setup(a => a.Request).Returns(request.Object);
|
||||
var requestContext = new Mock<RequestContext>();
|
||||
requestContext.Setup(a => a.HttpContext).Returns(requestContextBase.Object);
|
||||
var cachePolicy = new Mock<HttpCachePolicyBase>();
|
||||
cachePolicy.Setup(a => a.VaryByHeaders).Returns(new HttpCacheVaryByHeaders());
|
||||
//var httpContext = new Moq.Mock<ActionExecutingContext>();
|
||||
var response = new Mock<HttpResponseBase>();
|
||||
response.Setup(a => a.Headers).Returns(new System.Collections.Specialized.NameValueCollection());
|
||||
response.SetupProperty(a => a.Filter, new MemoryStream(Encoding.UTF8.GetBytes("awesome")) { });
|
||||
response.Setup(a => a.Cache).Returns(cachePolicy.Object);
|
||||
var responseContext = new Mock<HttpContextBase>();
|
||||
responseContext.Setup(a => a.Response).Returns(response.Object);
|
||||
|
||||
requestContextBase.Setup(a => a.Response).Returns(response.Object);
|
||||
var httpContext = new ResultExecutedContext()
|
||||
{
|
||||
RequestContext = new System.Web.Routing.RequestContext()
|
||||
{
|
||||
HttpContext = requestContextBase.Object
|
||||
},
|
||||
Exception = new Exception(),
|
||||
ExceptionHandled = true
|
||||
};
|
||||
CompressR.MVC.CompressFactory.Compress(httpContext, false);
|
||||
Assert.IsType<GZipStream>(httpContext.RequestContext.HttpContext.Response.Filter);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void ShouldDeflateWhenRequested()
|
||||
{
|
||||
var request = new Mock<HttpRequestBase>();
|
||||
request.Setup(a => a.Headers).Returns(new System.Collections.Specialized.NameValueCollection() { ["Accept-Encoding"] = "deflate" });
|
||||
var requestContextBase = new Mock<HttpContextBase>();
|
||||
requestContextBase.Setup(a => a.Request).Returns(request.Object);
|
||||
var requestContext = new Mock<RequestContext>();
|
||||
requestContext.Setup(a => a.HttpContext).Returns(requestContextBase.Object);
|
||||
var cachePolicy = new Mock<HttpCachePolicyBase>();
|
||||
cachePolicy.Setup(a => a.VaryByHeaders).Returns(new HttpCacheVaryByHeaders());
|
||||
//var httpContext = new Moq.Mock<ActionExecutingContext>();
|
||||
var response = new Mock<HttpResponseBase>();
|
||||
response.Setup(a => a.Headers).Returns(new System.Collections.Specialized.NameValueCollection());
|
||||
response.SetupProperty(a => a.Filter, new MemoryStream(Encoding.UTF8.GetBytes("awesome")) { });
|
||||
response.Setup(a => a.Cache).Returns(cachePolicy.Object);
|
||||
var responseContext = new Mock<HttpContextBase>();
|
||||
responseContext.Setup(a => a.Response).Returns(response.Object);
|
||||
|
||||
requestContextBase.Setup(a => a.Response).Returns(response.Object);
|
||||
var httpContext = new ResultExecutedContext()
|
||||
{
|
||||
RequestContext = new System.Web.Routing.RequestContext()
|
||||
{
|
||||
HttpContext = requestContextBase.Object
|
||||
}
|
||||
};
|
||||
|
||||
//httpContext.Setup(a=>a.RequestContext.Filter).Returns(new MemoryStream(Encoding.UTF8.GetBytes("awesome")) { } );
|
||||
//var response = new Mock<HttpResponseBase>();
|
||||
//httpContext.Setup(a => a.Response).Returns(response.Object);
|
||||
//var contextObject = httpContext;
|
||||
CompressR.MVC.CompressFactory.Compress(httpContext, false);
|
||||
Assert.IsType<DeflateStream>(httpContext.RequestContext.HttpContext.Response.Filter);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,11 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<packages>
|
||||
<package id="Castle.Core" version="3.3.3" targetFramework="net452" />
|
||||
<package id="Microsoft.AspNet.Mvc" version="5.2.3" targetFramework="net452" />
|
||||
<package id="Microsoft.AspNet.Razor" version="3.2.3" targetFramework="net452" />
|
||||
<package id="Microsoft.AspNet.WebPages" version="3.2.3" targetFramework="net452" />
|
||||
<package id="Microsoft.Web.Infrastructure" version="1.0.0.0" targetFramework="net452" />
|
||||
<package id="Moq" version="4.5.10" targetFramework="net452" />
|
||||
<package id="xunit" version="2.1.0" targetFramework="net452" />
|
||||
<package id="xunit.abstractions" version="2.0.0" targetFramework="net452" />
|
||||
<package id="xunit.assert" version="2.1.0" targetFramework="net452" />
|
||||
|
||||
141
src/CompressR.Owin.Sample/CompressR.Owin.Sample.csproj
Normal file
141
src/CompressR.Owin.Sample/CompressR.Owin.Sample.csproj
Normal file
@@ -0,0 +1,141 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<Import Project="..\..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.0\build\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props" Condition="Exists('..\..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.0\build\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props')" />
|
||||
<Import Project="..\..\packages\Microsoft.Net.Compilers.1.0.0\build\Microsoft.Net.Compilers.props" Condition="Exists('..\..\packages\Microsoft.Net.Compilers.1.0.0\build\Microsoft.Net.Compilers.props')" />
|
||||
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
|
||||
<PropertyGroup>
|
||||
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
|
||||
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
|
||||
<ProductVersion>
|
||||
</ProductVersion>
|
||||
<SchemaVersion>2.0</SchemaVersion>
|
||||
<ProjectGuid>{C6DD2187-F71A-4DA3-99B0-47A8CCF10853}</ProjectGuid>
|
||||
<ProjectTypeGuids>{349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>
|
||||
<OutputType>Library</OutputType>
|
||||
<AppDesignerFolder>Properties</AppDesignerFolder>
|
||||
<RootNamespace>CompressR.Owin.Sample</RootNamespace>
|
||||
<AssemblyName>CompressR.Owin.Sample</AssemblyName>
|
||||
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
|
||||
<UseIISExpress>true</UseIISExpress>
|
||||
<IISExpressSSLPort />
|
||||
<IISExpressAnonymousAuthentication />
|
||||
<IISExpressWindowsAuthentication />
|
||||
<IISExpressUseClassicPipelineMode />
|
||||
<UseGlobalApplicationHostFile />
|
||||
<NuGetPackageImportStamp>
|
||||
</NuGetPackageImportStamp>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
|
||||
<DebugSymbols>true</DebugSymbols>
|
||||
<DebugType>full</DebugType>
|
||||
<Optimize>false</Optimize>
|
||||
<OutputPath>bin\</OutputPath>
|
||||
<DefineConstants>DEBUG;TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
|
||||
<DebugType>pdbonly</DebugType>
|
||||
<Optimize>true</Optimize>
|
||||
<OutputPath>bin\</OutputPath>
|
||||
<DefineConstants>TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Reference Include="Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
|
||||
<HintPath>..\..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.0\lib\net45\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.dll</HintPath>
|
||||
<Private>True</Private>
|
||||
</Reference>
|
||||
<Reference Include="Microsoft.CSharp" />
|
||||
<Reference Include="Microsoft.Owin, Version=3.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
|
||||
<HintPath>..\..\packages\Microsoft.Owin.3.0.1\lib\net45\Microsoft.Owin.dll</HintPath>
|
||||
<Private>True</Private>
|
||||
</Reference>
|
||||
<Reference Include="Microsoft.Owin.Host.SystemWeb, Version=3.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
|
||||
<HintPath>..\..\packages\Microsoft.Owin.Host.SystemWeb.3.0.1\lib\net45\Microsoft.Owin.Host.SystemWeb.dll</HintPath>
|
||||
<Private>True</Private>
|
||||
</Reference>
|
||||
<Reference Include="Owin, Version=1.0.0.0, Culture=neutral, PublicKeyToken=f0ebd12fd5e55cc5, processorArchitecture=MSIL">
|
||||
<HintPath>..\..\packages\Owin.1.0\lib\net40\Owin.dll</HintPath>
|
||||
<Private>True</Private>
|
||||
</Reference>
|
||||
<Reference Include="System.Web.DynamicData" />
|
||||
<Reference Include="System.Web.Entity" />
|
||||
<Reference Include="System.Web.ApplicationServices" />
|
||||
<Reference Include="System.ComponentModel.DataAnnotations" />
|
||||
<Reference Include="System" />
|
||||
<Reference Include="System.Data" />
|
||||
<Reference Include="System.Core" />
|
||||
<Reference Include="System.Data.DataSetExtensions" />
|
||||
<Reference Include="System.Web.Extensions" />
|
||||
<Reference Include="System.Xml.Linq" />
|
||||
<Reference Include="System.Drawing" />
|
||||
<Reference Include="System.Web" />
|
||||
<Reference Include="System.Xml" />
|
||||
<Reference Include="System.Configuration" />
|
||||
<Reference Include="System.Web.Services" />
|
||||
<Reference Include="System.EnterpriseServices" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Content Include="packages.config" />
|
||||
<None Include="Web.Debug.config">
|
||||
<DependentUpon>Web.config</DependentUpon>
|
||||
</None>
|
||||
<None Include="Web.Release.config">
|
||||
<DependentUpon>Web.config</DependentUpon>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Content Include="Web.config" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="Properties\AssemblyInfo.cs" />
|
||||
<Compile Include="Startup.cs" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\CompressR.Owin\CompressR.Owin.csproj">
|
||||
<Project>{4b84a645-a7e3-446e-83b5-5f56d18b47df}</Project>
|
||||
<Name>CompressR.Owin</Name>
|
||||
</ProjectReference>
|
||||
</ItemGroup>
|
||||
<PropertyGroup>
|
||||
<VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">10.0</VisualStudioVersion>
|
||||
<VSToolsPath Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
|
||||
</PropertyGroup>
|
||||
<Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" />
|
||||
<Import Project="$(VSToolsPath)\WebApplications\Microsoft.WebApplication.targets" Condition="'$(VSToolsPath)' != ''" />
|
||||
<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v10.0\WebApplications\Microsoft.WebApplication.targets" Condition="false" />
|
||||
<ProjectExtensions>
|
||||
<VisualStudio>
|
||||
<FlavorProperties GUID="{349c5851-65df-11da-9384-00065b846f21}">
|
||||
<WebProjectProperties>
|
||||
<UseIIS>True</UseIIS>
|
||||
<AutoAssignPort>True</AutoAssignPort>
|
||||
<DevelopmentServerPort>42206</DevelopmentServerPort>
|
||||
<DevelopmentServerVPath>/</DevelopmentServerVPath>
|
||||
<IISUrl>http://localhost:42206/</IISUrl>
|
||||
<NTLMAuthentication>False</NTLMAuthentication>
|
||||
<UseCustomServer>False</UseCustomServer>
|
||||
<CustomServerUrl>
|
||||
</CustomServerUrl>
|
||||
<SaveServerSettingsInUserFile>False</SaveServerSettingsInUserFile>
|
||||
</WebProjectProperties>
|
||||
</FlavorProperties>
|
||||
</VisualStudio>
|
||||
</ProjectExtensions>
|
||||
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
|
||||
<PropertyGroup>
|
||||
<ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
|
||||
</PropertyGroup>
|
||||
<Error Condition="!Exists('..\..\packages\Microsoft.Net.Compilers.1.0.0\build\Microsoft.Net.Compilers.props')" Text="$([System.String]::Format('$(ErrorText)', '..\..\packages\Microsoft.Net.Compilers.1.0.0\build\Microsoft.Net.Compilers.props'))" />
|
||||
<Error Condition="!Exists('..\..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.0\build\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props')" Text="$([System.String]::Format('$(ErrorText)', '..\..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.0\build\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props'))" />
|
||||
</Target>
|
||||
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
|
||||
Other similar extension points exist, see Microsoft.Common.targets.
|
||||
<Target Name="BeforeBuild">
|
||||
</Target>
|
||||
<Target Name="AfterBuild">
|
||||
</Target>
|
||||
-->
|
||||
</Project>
|
||||
35
src/CompressR.Owin.Sample/Properties/AssemblyInfo.cs
Normal file
35
src/CompressR.Owin.Sample/Properties/AssemblyInfo.cs
Normal file
@@ -0,0 +1,35 @@
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
// General Information about an assembly is controlled through the following
|
||||
// set of attributes. Change these attribute values to modify the information
|
||||
// associated with an assembly.
|
||||
[assembly: AssemblyTitle("CompressR.Owin.Sample")]
|
||||
[assembly: AssemblyDescription("")]
|
||||
[assembly: AssemblyConfiguration("")]
|
||||
[assembly: AssemblyCompany("Tommy Parnell")]
|
||||
[assembly: AssemblyProduct("CompressR.Owin.Sample")]
|
||||
[assembly: AssemblyCopyright("Copyright © Tommy Parnell 2016")]
|
||||
[assembly: AssemblyTrademark("")]
|
||||
[assembly: AssemblyCulture("")]
|
||||
|
||||
// Setting ComVisible to false makes the types in this assembly not visible
|
||||
// to COM components. If you need to access a type in this assembly from
|
||||
// COM, set the ComVisible attribute to true on that type.
|
||||
[assembly: ComVisible(false)]
|
||||
|
||||
// The following GUID is for the ID of the typelib if this project is exposed to COM
|
||||
[assembly: Guid("c6dd2187-f71a-4da3-99b0-47a8ccf10853")]
|
||||
|
||||
// Version information for an assembly consists of the following four values:
|
||||
//
|
||||
// Major Version
|
||||
// Minor Version
|
||||
// Build Number
|
||||
// Revision
|
||||
//
|
||||
// You can specify all the values or you can default the Revision and Build Numbers
|
||||
// by using the '*' as shown below:
|
||||
[assembly: AssemblyVersion("1.5.2")]
|
||||
[assembly: AssemblyFileVersion("1.5.2")]
|
||||
21
src/CompressR.Owin.Sample/Startup.cs
Normal file
21
src/CompressR.Owin.Sample/Startup.cs
Normal file
@@ -0,0 +1,21 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Web;
|
||||
using Owin;
|
||||
|
||||
namespace CompressR.Owin.Sample
|
||||
{
|
||||
public class Startup
|
||||
{
|
||||
public void Configuration(IAppBuilder app)
|
||||
{
|
||||
app.Use<GzipMiddleware>();
|
||||
app.Run(context =>
|
||||
{
|
||||
context.Response.ContentType = "text/plain";
|
||||
return context.Response.WriteAsync("Hello World!");
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
30
src/CompressR.Owin.Sample/Web.Debug.config
Normal file
30
src/CompressR.Owin.Sample/Web.Debug.config
Normal file
@@ -0,0 +1,30 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
|
||||
<!-- For more information on using web.config transformation visit http://go.microsoft.com/fwlink/?LinkId=125889 -->
|
||||
|
||||
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
|
||||
<!--
|
||||
In the example below, the "SetAttributes" transform will change the value of
|
||||
"connectionString" to use "ReleaseSQLServer" only when the "Match" locator
|
||||
finds an attribute "name" that has a value of "MyDB".
|
||||
|
||||
<connectionStrings>
|
||||
<add name="MyDB"
|
||||
connectionString="Data Source=ReleaseSQLServer;Initial Catalog=MyReleaseDB;Integrated Security=True"
|
||||
xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
|
||||
</connectionStrings>
|
||||
-->
|
||||
<system.web>
|
||||
<!--
|
||||
In the example below, the "Replace" transform will replace the entire
|
||||
<customErrors> section of your web.config file.
|
||||
Note that because there is only one customErrors section under the
|
||||
<system.web> node, there is no need to use the "xdt:Locator" attribute.
|
||||
|
||||
<customErrors defaultRedirect="GenericError.htm"
|
||||
mode="RemoteOnly" xdt:Transform="Replace">
|
||||
<error statusCode="500" redirect="InternalError.htm"/>
|
||||
</customErrors>
|
||||
-->
|
||||
</system.web>
|
||||
</configuration>
|
||||
31
src/CompressR.Owin.Sample/Web.Release.config
Normal file
31
src/CompressR.Owin.Sample/Web.Release.config
Normal file
@@ -0,0 +1,31 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
|
||||
<!-- For more information on using web.config transformation visit http://go.microsoft.com/fwlink/?LinkId=125889 -->
|
||||
|
||||
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
|
||||
<!--
|
||||
In the example below, the "SetAttributes" transform will change the value of
|
||||
"connectionString" to use "ReleaseSQLServer" only when the "Match" locator
|
||||
finds an attribute "name" that has a value of "MyDB".
|
||||
|
||||
<connectionStrings>
|
||||
<add name="MyDB"
|
||||
connectionString="Data Source=ReleaseSQLServer;Initial Catalog=MyReleaseDB;Integrated Security=True"
|
||||
xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
|
||||
</connectionStrings>
|
||||
-->
|
||||
<system.web>
|
||||
<compilation xdt:Transform="RemoveAttributes(debug)" />
|
||||
<!--
|
||||
In the example below, the "Replace" transform will replace the entire
|
||||
<customErrors> section of your web.config file.
|
||||
Note that because there is only one customErrors section under the
|
||||
<system.web> node, there is no need to use the "xdt:Locator" attribute.
|
||||
|
||||
<customErrors defaultRedirect="GenericError.htm"
|
||||
mode="RemoteOnly" xdt:Transform="Replace">
|
||||
<error statusCode="500" redirect="InternalError.htm"/>
|
||||
</customErrors>
|
||||
-->
|
||||
</system.web>
|
||||
</configuration>
|
||||
21
src/CompressR.Owin.Sample/Web.config
Normal file
21
src/CompressR.Owin.Sample/Web.config
Normal file
@@ -0,0 +1,21 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!--
|
||||
For more information on how to configure your ASP.NET application, please visit
|
||||
http://go.microsoft.com/fwlink/?LinkId=169433
|
||||
-->
|
||||
<configuration>
|
||||
<system.web>
|
||||
<compilation debug="true" targetFramework="4.5.2"/>
|
||||
<httpRuntime targetFramework="4.5.2"/>
|
||||
</system.web>
|
||||
<system.codedom>
|
||||
<compilers>
|
||||
<compiler language="c#;cs;csharp" extension=".cs"
|
||||
type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
|
||||
warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701"/>
|
||||
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb"
|
||||
type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
|
||||
warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+"/>
|
||||
</compilers>
|
||||
</system.codedom>
|
||||
</configuration>
|
||||
8
src/CompressR.Owin.Sample/packages.config
Normal file
8
src/CompressR.Owin.Sample/packages.config
Normal file
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<packages>
|
||||
<package id="Microsoft.CodeDom.Providers.DotNetCompilerPlatform" version="1.0.0" targetFramework="net452" />
|
||||
<package id="Microsoft.Net.Compilers" version="1.0.0" targetFramework="net452" developmentDependency="true" />
|
||||
<package id="Microsoft.Owin" version="3.0.1" targetFramework="net452" />
|
||||
<package id="Microsoft.Owin.Host.SystemWeb" version="3.0.1" targetFramework="net452" />
|
||||
<package id="Owin" version="1.0" targetFramework="net452" />
|
||||
</packages>
|
||||
65
src/CompressR.Owin/CompressR.Owin.csproj
Normal file
65
src/CompressR.Owin/CompressR.Owin.csproj
Normal file
@@ -0,0 +1,65 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
|
||||
<PropertyGroup>
|
||||
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
|
||||
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
|
||||
<ProjectGuid>{4B84A645-A7E3-446E-83B5-5F56D18B47DF}</ProjectGuid>
|
||||
<OutputType>Library</OutputType>
|
||||
<AppDesignerFolder>Properties</AppDesignerFolder>
|
||||
<RootNamespace>CompressR.Owin</RootNamespace>
|
||||
<AssemblyName>CompressR.Owin</AssemblyName>
|
||||
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
|
||||
<FileAlignment>512</FileAlignment>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
|
||||
<DebugSymbols>true</DebugSymbols>
|
||||
<DebugType>full</DebugType>
|
||||
<Optimize>false</Optimize>
|
||||
<OutputPath>bin\Debug\</OutputPath>
|
||||
<DefineConstants>DEBUG;TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
|
||||
<DebugType>pdbonly</DebugType>
|
||||
<Optimize>true</Optimize>
|
||||
<OutputPath>bin\Release\</OutputPath>
|
||||
<DefineConstants>TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Reference Include="Microsoft.Owin, Version=3.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
|
||||
<HintPath>..\..\packages\Microsoft.Owin.3.0.1\lib\net45\Microsoft.Owin.dll</HintPath>
|
||||
<Private>True</Private>
|
||||
</Reference>
|
||||
<Reference Include="Owin, Version=1.0.0.0, Culture=neutral, PublicKeyToken=f0ebd12fd5e55cc5, processorArchitecture=MSIL">
|
||||
<HintPath>..\..\packages\Owin.1.0\lib\net40\Owin.dll</HintPath>
|
||||
<Private>True</Private>
|
||||
</Reference>
|
||||
<Reference Include="System" />
|
||||
<Reference Include="System.Core" />
|
||||
<Reference Include="System.Xml.Linq" />
|
||||
<Reference Include="System.Data.DataSetExtensions" />
|
||||
<Reference Include="Microsoft.CSharp" />
|
||||
<Reference Include="System.Data" />
|
||||
<Reference Include="System.Net.Http" />
|
||||
<Reference Include="System.Xml" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="CompressionMiddleware.cs" />
|
||||
<Compile Include="Properties\AssemblyInfo.cs" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<None Include="packages.config" />
|
||||
</ItemGroup>
|
||||
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
|
||||
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
|
||||
Other similar extension points exist, see Microsoft.Common.targets.
|
||||
<Target Name="BeforeBuild">
|
||||
</Target>
|
||||
<Target Name="AfterBuild">
|
||||
</Target>
|
||||
-->
|
||||
</Project>
|
||||
17
src/CompressR.Owin/CompressR.Owin.nuspec
Normal file
17
src/CompressR.Owin/CompressR.Owin.nuspec
Normal file
@@ -0,0 +1,17 @@
|
||||
<?xml version="1.0"?>
|
||||
<package>
|
||||
<metadata>
|
||||
<id>$id$</id>
|
||||
<version>$version$</version>
|
||||
<title>$title$</title>
|
||||
<authors>$author$</authors>
|
||||
<owners>$author$</owners>
|
||||
<licenseUrl>https://opensource.org/licenses/MIT</licenseUrl>
|
||||
<projectUrl>https://github.com/tparnell8/CompressR</projectUrl>
|
||||
<requireLicenseAcceptance>false</requireLicenseAcceptance>
|
||||
<description>Compress owin actions!</description>
|
||||
<releaseNotes></releaseNotes>
|
||||
<copyright>Copyright 2016</copyright>
|
||||
<tags>Compression Owin</tags>
|
||||
</metadata>
|
||||
</package>
|
||||
54
src/CompressR.Owin/CompressionMiddleware.cs
Normal file
54
src/CompressR.Owin/CompressionMiddleware.cs
Normal file
@@ -0,0 +1,54 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.IO.Compression;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Owin;
|
||||
|
||||
namespace CompressR.Owin
|
||||
{
|
||||
public struct Constants
|
||||
{
|
||||
public const string Gzip = "gzip";
|
||||
public const string Deflate = "deflate";
|
||||
public const string ContentEncoding = "Content-Encoding";
|
||||
public const string AcceptEncoding = "Accept-Encoding";
|
||||
public static readonly string[] Compressors = { Gzip, Deflate };
|
||||
}
|
||||
|
||||
public class GzipMiddleware : OwinMiddleware
|
||||
{
|
||||
public GzipMiddleware(OwinMiddleware next) : base(next)
|
||||
{
|
||||
}
|
||||
|
||||
public async override Task Invoke(IOwinContext context)
|
||||
{
|
||||
if(!context.Request.Headers.Keys.Contains(Constants.AcceptEncoding))
|
||||
{
|
||||
await Next.Invoke(context);
|
||||
}
|
||||
var types = context.Request.Headers[Constants.AcceptEncoding].Split(',');
|
||||
if(types.Contains(Constants.Gzip, StringComparer.OrdinalIgnoreCase))
|
||||
{
|
||||
var responseStream = context.Response.Body;
|
||||
using(var memStream = new MemoryStream())
|
||||
{
|
||||
context.Response.Body = memStream;
|
||||
await Next?.Invoke(context);
|
||||
context.Response.Headers[Constants.ContentEncoding] = Constants.Gzip;
|
||||
using(var gzipStream = new GZipStream(responseStream, CompressionLevel.Optimal))
|
||||
{
|
||||
memStream.WriteTo(gzipStream);
|
||||
await gzipStream.FlushAsync();
|
||||
}
|
||||
|
||||
await responseStream.FlushAsync();
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
36
src/CompressR.Owin/Properties/AssemblyInfo.cs
Normal file
36
src/CompressR.Owin/Properties/AssemblyInfo.cs
Normal file
@@ -0,0 +1,36 @@
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
// General Information about an assembly is controlled through the following
|
||||
// set of attributes. Change these attribute values to modify the information
|
||||
// associated with an assembly.
|
||||
[assembly: AssemblyTitle("CompressR.Owin")]
|
||||
[assembly: AssemblyDescription("")]
|
||||
[assembly: AssemblyConfiguration("")]
|
||||
[assembly: AssemblyCompany("Tommy Parnell")]
|
||||
[assembly: AssemblyProduct("CompressR.Owin")]
|
||||
[assembly: AssemblyCopyright("Copyright © Tommy Parnell 2016")]
|
||||
[assembly: AssemblyTrademark("")]
|
||||
[assembly: AssemblyCulture("")]
|
||||
|
||||
// Setting ComVisible to false makes the types in this assembly not visible
|
||||
// to COM components. If you need to access a type in this assembly from
|
||||
// COM, set the ComVisible attribute to true on that type.
|
||||
[assembly: ComVisible(false)]
|
||||
|
||||
// The following GUID is for the ID of the typelib if this project is exposed to COM
|
||||
[assembly: Guid("4b84a645-a7e3-446e-83b5-5f56d18b47df")]
|
||||
|
||||
// Version information for an assembly consists of the following four values:
|
||||
//
|
||||
// Major Version
|
||||
// Minor Version
|
||||
// Build Number
|
||||
// Revision
|
||||
//
|
||||
// You can specify all the values or you can default the Build and Revision Numbers
|
||||
// by using the '*' as shown below:
|
||||
// [assembly: AssemblyVersion("1.5.2")]
|
||||
[assembly: AssemblyVersion("1.5.2")]
|
||||
[assembly: AssemblyFileVersion("1.5.2")]
|
||||
5
src/CompressR.Owin/packages.config
Normal file
5
src/CompressR.Owin/packages.config
Normal file
@@ -0,0 +1,5 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<packages>
|
||||
<package id="Microsoft.Owin" version="3.0.1" targetFramework="net452" />
|
||||
<package id="Owin" version="1.0" targetFramework="net452" />
|
||||
</packages>
|
||||
@@ -14,7 +14,21 @@ namespace CompressR.Sample.Controllers
|
||||
{
|
||||
ViewBag.Title = "Home Page";
|
||||
|
||||
return View();
|
||||
return View("index");
|
||||
}
|
||||
[Gzip]
|
||||
public ActionResult Gzip()
|
||||
{
|
||||
ViewBag.Title = "Home Page";
|
||||
|
||||
return View("index");
|
||||
}
|
||||
[Deflate]
|
||||
public ActionResult Deflate()
|
||||
{
|
||||
ViewBag.Title = "Home Page";
|
||||
|
||||
return View("index");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,11 @@
|
||||
using CompressR.WebApi;
|
||||
using System;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Threading.Tasks;
|
||||
using System.Web.Http;
|
||||
using CompressR.WebApi;
|
||||
|
||||
namespace CompressR.Sample.Controllers
|
||||
{
|
||||
@@ -17,6 +17,7 @@ namespace CompressR.Sample.Controllers
|
||||
{
|
||||
return new string[] { "value1", "value2" };
|
||||
}
|
||||
[Deflate]
|
||||
|
||||
// GET api/values/5
|
||||
public string Get(int id)
|
||||
@@ -24,7 +25,7 @@ namespace CompressR.Sample.Controllers
|
||||
return "value";
|
||||
}
|
||||
|
||||
[Compress]
|
||||
[Gzip]
|
||||
[HttpGet, Route("TestJsonSerialization")]
|
||||
public async Task<IHttpActionResult> TestJsonSerialization()
|
||||
{
|
||||
@@ -32,7 +33,6 @@ namespace CompressR.Sample.Controllers
|
||||
{
|
||||
A = 1,
|
||||
B = new string[] { "1", "A", "B" }
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
@@ -44,9 +44,7 @@ namespace CompressR.Sample.Controllers
|
||||
{
|
||||
A = 1,
|
||||
B = new string[] { "1", "A", "B" }
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
55
src/CompressR.WebApi/BaseCompressAttribute.cs
Normal file
55
src/CompressR.WebApi/BaseCompressAttribute.cs
Normal file
@@ -0,0 +1,55 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO.Compression;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.Web.Http.Filters;
|
||||
using CompressR.Exceptions;
|
||||
|
||||
namespace CompressR.WebApi
|
||||
{
|
||||
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
|
||||
public abstract class BaseCompressAttribute : System.Web.Http.Filters.ActionFilterAttribute
|
||||
{
|
||||
protected bool RequireCompression { get; set; }
|
||||
public CompressionLevel CompressionLevel { get; set; } = CompressionLevel.Optimal;
|
||||
|
||||
protected BaseCompressAttribute(bool requireCompression = false)
|
||||
{
|
||||
RequireCompression = requireCompression;
|
||||
}
|
||||
|
||||
protected async Task CompressAction(HttpActionExecutedContext actionExecutedContext, params string[] compressors)
|
||||
{
|
||||
if(actionExecutedContext?.Exception != null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
if(actionExecutedContext?.Response?.Content == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
var acceptedEncoding = actionExecutedContext
|
||||
.Response
|
||||
.RequestMessage
|
||||
.Headers
|
||||
.AcceptEncoding
|
||||
.Select(a => a.Value)
|
||||
.Intersect(compressors, StringComparer.OrdinalIgnoreCase)
|
||||
.FirstOrDefault();
|
||||
|
||||
if(string.IsNullOrWhiteSpace(acceptedEncoding))
|
||||
{
|
||||
if(RequireCompression)
|
||||
{
|
||||
throw new CompressRException("Compression required but client did not send accept header");
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
actionExecutedContext.Response.Content = new CompressedContent(actionExecutedContext.Response.Content, acceptedEncoding, CompressionLevel);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,62 +1,26 @@
|
||||
using CompressR.Exceptions;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO.Compression;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.Web.Http.Controllers;
|
||||
using System.Web.Http.Filters;
|
||||
|
||||
namespace CompressR.WebApi
|
||||
{
|
||||
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
|
||||
public sealed class CompressAttribute : System.Web.Http.Filters.ActionFilterAttribute
|
||||
public sealed class CompressAttribute : BaseCompressAttribute
|
||||
{
|
||||
private bool RequireCompression { get; set; }
|
||||
|
||||
public CompressAttribute(bool requireCompression = false)
|
||||
{
|
||||
RequireCompression = requireCompression;
|
||||
}
|
||||
: base(requireCompression) { }
|
||||
|
||||
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
|
||||
{
|
||||
OnActionExecutedAsync(actionExecutedContext, CancellationToken.None).Wait();
|
||||
|
||||
base.CompressAction(actionExecutedContext, Constants.Compressors).Wait();
|
||||
}
|
||||
|
||||
public override async Task OnActionExecutedAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)
|
||||
public override Task OnActionExecutedAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)
|
||||
{
|
||||
if(actionExecutedContext.Response.Content == null)
|
||||
if(cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
return;
|
||||
return Task.FromResult(0);
|
||||
}
|
||||
var acceptedEncoding = actionExecutedContext
|
||||
.Response
|
||||
.RequestMessage
|
||||
.Headers
|
||||
.AcceptEncoding
|
||||
.Select(a => a.Value)
|
||||
.Intersect(Constants.Compressors, StringComparer.OrdinalIgnoreCase)
|
||||
.FirstOrDefault();
|
||||
|
||||
if (string.IsNullOrWhiteSpace(acceptedEncoding))
|
||||
{
|
||||
if (RequireCompression)
|
||||
{
|
||||
throw new CompressRException("Compression required but client did not send accept header");
|
||||
}
|
||||
else
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
actionExecutedContext.Response.Content = new CompressedContent(actionExecutedContext.Response.Content, acceptedEncoding);
|
||||
return base.CompressAction(actionExecutedContext, Constants.Compressors);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -53,6 +53,7 @@
|
||||
<Reference Include="System.Xml" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="BaseCompressAttribute.cs" />
|
||||
<Compile Include="CompressedContent.cs" />
|
||||
<Compile Include="Constants.cs" />
|
||||
<Compile Include="DeflateAttribute.cs" />
|
||||
|
||||
@@ -9,12 +9,13 @@ namespace CompressR.WebApi
|
||||
{
|
||||
public class CompressedContent : HttpContent
|
||||
{
|
||||
private readonly CompressionLevel compressionLevel;
|
||||
private readonly string _encodingType;
|
||||
private readonly HttpContent _originalContent;
|
||||
|
||||
public CompressedContent(HttpContent content, string encodingType = "gzip")
|
||||
public CompressedContent(HttpContent content, string encodingType = "gzip", CompressionLevel compressionLevel = CompressionLevel.Optimal)
|
||||
{
|
||||
if (content == null)
|
||||
if(content == null)
|
||||
{
|
||||
throw new ArgumentNullException("content");
|
||||
}
|
||||
@@ -22,11 +23,12 @@ namespace CompressR.WebApi
|
||||
_originalContent = content;
|
||||
_encodingType = encodingType.ToLowerInvariant();
|
||||
|
||||
foreach (var header in _originalContent.Headers)
|
||||
foreach(var header in _originalContent.Headers)
|
||||
{
|
||||
Headers.TryAddWithoutValidation(header.Key, header.Value);
|
||||
}
|
||||
Headers.ContentEncoding.Add(encodingType);
|
||||
this.compressionLevel = compressionLevel;
|
||||
}
|
||||
|
||||
protected override bool TryComputeLength(out long length)
|
||||
@@ -38,14 +40,14 @@ namespace CompressR.WebApi
|
||||
protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
|
||||
{
|
||||
Stream compressedStream = null;
|
||||
switch (_encodingType)
|
||||
switch(_encodingType)
|
||||
{
|
||||
case Constants.Gzip:
|
||||
compressedStream = new GZipStream(stream, CompressionMode.Compress, true);
|
||||
compressedStream = new GZipStream(stream, compressionLevel, true);
|
||||
break;
|
||||
|
||||
case Constants.Deflate:
|
||||
compressedStream = new DeflateStream(stream, CompressionMode.Compress, true);
|
||||
compressedStream = new DeflateStream(stream, compressionLevel, true);
|
||||
break;
|
||||
|
||||
default:
|
||||
@@ -55,7 +57,7 @@ namespace CompressR.WebApi
|
||||
|
||||
return _originalContent.CopyToAsync(compressedStream).ContinueWith(tsk =>
|
||||
{
|
||||
if (compressedStream != null)
|
||||
if(compressedStream != null)
|
||||
{
|
||||
compressedStream.Dispose();
|
||||
}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
using CompressR.Exceptions;
|
||||
using System;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO.Compression;
|
||||
using System.Linq;
|
||||
@@ -9,49 +8,27 @@ using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.Web.Http.Controllers;
|
||||
using System.Web.Http.Filters;
|
||||
using CompressR.Exceptions;
|
||||
|
||||
namespace CompressR.WebApi
|
||||
{
|
||||
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
|
||||
public sealed class DeflateAttribute : System.Web.Http.Filters.ActionFilterAttribute
|
||||
public sealed class DeflateAttribute : BaseCompressAttribute
|
||||
{
|
||||
private bool RequireCompression { get; set; }
|
||||
|
||||
public DeflateAttribute(bool requireCompression = false)
|
||||
{
|
||||
RequireCompression = requireCompression;
|
||||
}
|
||||
: base(requireCompression) { }
|
||||
|
||||
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
|
||||
{
|
||||
OnActionExecutedAsync(actionExecutedContext, CancellationToken.None).Wait();
|
||||
base.CompressAction(actionExecutedContext, Constants.Deflate).Wait();
|
||||
}
|
||||
|
||||
public override async Task OnActionExecutedAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)
|
||||
public override Task OnActionExecutedAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)
|
||||
{
|
||||
if(actionExecutedContext.Response.Content == null)
|
||||
if(cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
return;
|
||||
return Task.FromResult(0);
|
||||
}
|
||||
var acceptedEncoding = actionExecutedContext
|
||||
.Response
|
||||
.RequestMessage
|
||||
.Headers
|
||||
.AcceptEncoding
|
||||
.Select(a => a.Value)
|
||||
.Any(a => a.Equals(Constants.Deflate, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
if (!acceptedEncoding && RequireCompression)
|
||||
{
|
||||
throw new CompressRException("Compression required but client did not send accept header");
|
||||
}
|
||||
|
||||
if (!acceptedEncoding)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
actionExecutedContext.Response.Content = new CompressedContent(actionExecutedContext.Response.Content, Constants.Deflate);
|
||||
return base.CompressAction(actionExecutedContext, Constants.Deflate);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
using CompressR.Exceptions;
|
||||
using System;
|
||||
using System;
|
||||
using System.IO.Compression;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
@@ -8,50 +7,27 @@ using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.Web.Http.Controllers;
|
||||
using System.Web.Http.Filters;
|
||||
using CompressR.Exceptions;
|
||||
|
||||
namespace CompressR.WebApi
|
||||
{
|
||||
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
|
||||
public sealed class GzipAttribute : System.Web.Http.Filters.ActionFilterAttribute
|
||||
public sealed class GzipAttribute : BaseCompressAttribute
|
||||
{
|
||||
private bool RequireCompression { get; set; }
|
||||
|
||||
public GzipAttribute(bool requireCompression = false)
|
||||
{
|
||||
RequireCompression = requireCompression;
|
||||
}
|
||||
: base(requireCompression) { }
|
||||
|
||||
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
|
||||
{
|
||||
OnActionExecutedAsync(actionExecutedContext, CancellationToken.None).Wait();
|
||||
base.CompressAction(actionExecutedContext, Constants.Gzip).Wait();
|
||||
}
|
||||
|
||||
public override async Task OnActionExecutedAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)
|
||||
public override Task OnActionExecutedAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)
|
||||
{
|
||||
if(actionExecutedContext.Response.Content == null)
|
||||
if(cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
return;
|
||||
return Task.FromResult(0);
|
||||
}
|
||||
var acceptedEncoding = actionExecutedContext
|
||||
.Response
|
||||
.RequestMessage
|
||||
.Headers
|
||||
.AcceptEncoding
|
||||
.Select(a => a.Value)
|
||||
.Any(a => a.Equals(Constants.Gzip, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
|
||||
if (!acceptedEncoding && RequireCompression)
|
||||
{
|
||||
throw new CompressRException("Compression required but client did not send accept header");
|
||||
}
|
||||
|
||||
if (!acceptedEncoding)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
actionExecutedContext.Response.Content = new CompressedContent(actionExecutedContext.Response.Content, Constants.Gzip);
|
||||
return base.CompressAction(actionExecutedContext, Constants.Gzip);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user