.netasp.net-mvcvb.netimageresizer

How to add Access-Control-Allow-Origin header with an ImageResizer plugin


The extensions point page in the ImageResizer docs mention that plugins can "Modify http headers" but they don't have any direction or example on how to do so. I created a plugin that implements both the IPlugin and IChache interfaces to add the HTTP header but it doesn't feel right because:

  1. I do NOT want to implement or create "an alternate caching system"
  2. It does not work (the image does not display/displays as a blank image) if I do not include the code current.RemapHandler(New NoCacheHandler(e)) at the end of the Process() method. I don't understand what this line is doing or the implications of remapping the handler

Here is my current implementation

web.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    ...
    <resizer>
        <plugins>
            <add name="MyNamespace.CorsHeadersPlugin" />
            <add name="Watermark" />
            <add name="MvcRoutingShim" />
            <add name="PsdReader" />
            <add name="WicDecoder" />
            <add name="WicEncoder" />
            <add name="WicBuilder" />
        </plugins>
    </resizer>
    ...
</configuration>

CorsHeadersPlugin

Imports ImageResizer.Caching
Imports ImageResizer.Configuration
Imports ImageResizer.Plugins
Imports ImageResizer.Plugins.Basic

Public Class CorsHeadersPlugin
    Implements IPlugin
    Implements ICache

    Private ReadOnly AllowedDomains As String()

    Public Sub New()
        AllowedDomains = {"http://allowthisdomain.com"}

#If DEBUG Then
        AllowedDomains = AllowedDomains.Union({"http://localhost", "https://localhost"}).ToArray
#End If
    End Sub

    Public Function CanProcess(current As HttpContext, e As IResponseArgs) As Boolean Implements ICache.CanProcess
        Return True
    End Function

    Public Sub Process(current As HttpContext, e As IResponseArgs) Implements ICache.Process
        Dim origin = current.Request.Url.GetLeftPart(UriPartial.Authority)

        If AllowedDomains.Contains(origin) Then
            current.Response.Headers.Add("Access-Control-Allow-Origin", origin)
        End If

        current.RemapHandler(New NoCacheHandler(e))
    End Sub

    Public Function Install(c As Config) As IPlugin Implements IPlugin.Install
        c.Plugins.add_plugin(Me)
        Return Me
    End Function

    Public Function Uninstall(c As Config) As Boolean Implements IPlugin.Uninstall
        c.Plugins.remove_plugin(Me)
        Return True
    End Function
End Class

Solution

  • The event handlers ImageResizer.Config.Current.Pipeline.PreHandleImage and .PreHandleImageAsync allow you to modify the response headers. Make sure to only register handlers once during AppStart.