egil / Htmxor

Supercharges Blazor static server side rendering (SSR) by seamlessly integrating the Htmx.org frontend library.
MIT License
124 stars 13 forks source link

Control any response headers from a component #18

Open egil opened 5 months ago

egil commented 5 months ago

Htmxor should include a generic way for developers to declaratively influence any headers during when returning a response to a request, not just the htmx specific headers that are exposed via the HtmxContext.Response, aka. HtmxResponse object.

There are two scenarios in play:

Headers that are dynamically set based on request or dynamic content: Right now, developers can [Inject] private HttpContext Ctx in a component and set response headers through that. For convenience, this could also be enabled through a generic Headers property on the HtmxResponse type, which would just point to the HtmlContext.Response.Headers dictionary.

Headers that are statically determined at compile time: These are good candidates for a declarative approach. My idea is for Htmxor to include a IControlResponseHeaders interface, that any attribute can implement. Then, developers can implement custom attributes that implement this interface and use these attributes in their components declaratively.

Here is the interface definition:

public interface IControlResponseHeaders
{
    void Apply(IHeaderDictionary headers);
}

And an example attribute:

[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)]
public sealed class ContentLanguageAttribute(string language) : Attribute, IControlResponseHeaders
{
  public void Apply(IHeaderDictionary headers)
  {
    headers["Content-Language"] = language;
  }
}

This can then be used like this:

@attribute [ContentLanguage("da-DK")]
@page "/da/home"
...

Inspired by: https://mastodon.social/@khalidabuhakmeh/112339241113769565