How to disable auto download when access pdf file?

2025/10/16 2:49 AM

When I access image file, it's show preview image on browser, but when access pdf file, it show download popup, could I show preview pdf instead download popup like image?


Environment

  • Xperience by Kentico version: 30.10.0

  • .NET version: 8

Answers

2025/10/16 4:10 AM
Accepted answer

The Content-Disposition response header determines whether a PDF file opens in the browser as a preview or is downloaded. XbyK sets this value to attachment, which forces the file to download. To allow the PDF to open inline, the value needs to be changed to inline. Since this cannot be configured through the Admin UI, the solution is to add a middleware. Here it is.

/// <summary>
/// Middleware that modifies the Content-Disposition header for PDF files to display them inline
/// instead of forcing download. This allows PDFs to be viewed directly in the browser.
/// </summary>
public class PdfInlineMiddleware
{
    private readonly RequestDelegate _next;

    public PdfInlineMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        context.Response.OnStarting(() =>
        {
            // Check if the response is a PDF file
            if (IsPdfFile(context.Response))
            {
                // Get the existing Content-Disposition header
                var existingDisposition = context
                    .Response.Headers["Content-Disposition"]
                    .FirstOrDefault();

                if (!string.IsNullOrEmpty(existingDisposition))
                {
                    // Extract filename from existing disposition
                    var filename = ExtractFilenameFromDisposition(existingDisposition);

                    // Set Content-Disposition to inline with preserved filename
                    context.Response.Headers["Content-Disposition"] = string.IsNullOrEmpty(filename)
                        ? "inline"
                        : $"inline; filename=\"{filename}\"";
                }
                else
                {
                    // No existing disposition, just set to inline
                    context.Response.Headers.Append("Content-Disposition", "inline");
                }
            }

            return Task.CompletedTask;
        });

        await _next(context);
    }

    /// <summary>
    /// Determines if the response is a PDF file based on Content-Type header
    /// </summary>
    /// <param name="response">The HTTP response</param>
    /// <returns>True if the response is a PDF file, false otherwise</returns>
    private static bool IsPdfFile(HttpResponse response)
    {
        var contentType = response.ContentType;
        return !string.IsNullOrEmpty(contentType)
            && contentType.Equals("application/pdf", StringComparison.OrdinalIgnoreCase);
    }

    /// <summary>
    /// Extracts the filename from a Content-Disposition header value
    /// </summary>
    /// <param name="disposition">The Content-Disposition header value</param>
    /// <returns>The filename if found, null otherwise</returns>
    private static string ExtractFilenameFromDisposition(string disposition)
    {
        if (string.IsNullOrEmpty(disposition))
            return null;

        // Look for filename= pattern (with or without quotes)
        var filenameMatch = System.Text.RegularExpressions.Regex.Match(
            disposition,
            @"filename\s*=\s*[""']?([^""'\s;]+)[""']?",
            System.Text.RegularExpressions.RegexOptions.IgnoreCase
        );

        return filenameMatch.Success ? filenameMatch.Groups[1].Value : null;
    }
}

And then in your Program.cs file:

app.UseMiddleware<PdfInlineMiddleware>();

To response this discussion, you have to login first.