Skip to content

Latest commit

 

History

History
166 lines (133 loc) · 8.77 KB

runtime-api.md

File metadata and controls

166 lines (133 loc) · 8.77 KB

Runtime API

Astro docs: Render context

The Astro global is ambient in every .razor page and component — no import and no @inherits. It arrives through a generated _Imports.razor carrying @inject AstroSharp.AstroContext Astro.

It covers 22 of the 24 members of Astro's own render context, plus Astro.slots, which Astro documents separately.

The mapping

Astro AstroSharp
Astro.url Astro.Url (Uri)
Astro.site Astro.Site
Astro.generator Astro.Generator
Astro.params Astro.Params
Astro.props Astro.Props — Get<T>(key), GetString(key), Has(key)
Astro.locals Astro.Locals — same accessors, plus Set
Astro.request Astro.Request — .NET's own HttpRequestMessage. Header(name), Query(name) and ReadJsonAsync<T>() are extensions on it.
Astro.cookies Astro.Cookies — Get, Has, Set, Delete. On the context rather than the request, as in Astro. Writing needs an on-demand route. merge(), headers() and consume() have no counterpart: the first takes another AstroCookies instance, and the last two exist for adapters emitting the response.
Astro.slots Astro.Slots — Has, Names, Render
Astro.response Astro.Response — Status, SetHeader, and Headers with Set / Append / Get / GetAll, mirroring the web's Headers. A header set by a page reaches the response; one set by a component does not, exactly as in Astro. See below.
Astro.redirect() Astro.Redirect(location, status)
Astro.clientAddress Astro.ClientAddress
Astro.currentLocale Astro.CurrentLocale
Astro.preferredLocale Astro.PreferredLocale
Astro.preferredLocaleList Astro.PreferredLocaleList
Astro.originPathname Astro.OriginPathname
Astro.routePattern Astro.RoutePattern
Astro.isPrerendered Astro.IsPrerendered
Astro.session Astro.Session — synchronous; check IsAvailable
Astro.cache Astro.Cache — check Enabled
Astro.csp Astro.Csp — check IsAvailable
Astro.logger Astro.Logger — Info, Warn, Error; works everywhere
Astro.getActionResult() Astro.GetActionResult(name) — by name, since C# has no reference to the action function
Astro.rewrite() Not available. See below.
Astro.callAction() Not available, and not needed. See below.

Members with no Astro counterpart

These stand in for modules a .razor file cannot import:

AstroSharp Stands in for
Astro.Content getCollection() / getEntry() from astro:content
Astro.Assets getImage() from astro:assets
Astro.I18n the locale URL helpers from astro:i18n
Astro.Env typed variables from astro:env
Astro.Meta import.meta.env — BASE_URL, DEV, MODE, SITE
Astro.Config astro:config — unwrapped; reached with Defer / CallAsync
Astro.Transitions astro:transitions — unwrapped, as above
Astro.Module(spec) any other module
Astro.Vars(values) define:vars on a <style>
Astro.RawHtml(value) asking for a function prop's value as markup

Content and Assets call back into Astro and are therefore async — await them from OnInitializedAsync. I18n and Env are resolved locally and are synchronous, so they work straight from markup.

Astro.Cookies

---
// .astro
const theme = Astro.cookies.get('theme')?.value;
Astro.cookies.set('seen', 'yes', { path: '/', httpOnly: true, maxAge: 60 });
Astro.cookies.delete('stale', { path: '/' });
---
@code {
    protected override void OnInitialized()
    {
        Astro.Cookies.Set("seen", "yes", new CookieOptions { Path = "/", HttpOnly = true, MaxAge = 60 });
        Astro.Cookies.Delete("stale", new CookieOptions { Path = "/" });
    }
}

<p>@(Astro.Cookies.Get("theme")?.Value ?? "default")</p>

CookieOptions carries Astro's own option names — Domain, Expires, HttpOnly, MaxAge, Path, SameSite, Secure — and every one is optional. An option you do not set is not sent, so Astro's default applies rather than one of AstroSharp's.

A value that is not a string is written as JSON, matching Astro, and Get(...).Json<T>() reads it back:

Astro.Cookies.Set("prefs", new Prefs("dark"));       // {"theme":"dark"}
var prefs = Astro.Cookies.Get("prefs")?.Json<Prefs>();

Writes are recorded and replayed onto Astro's own cookie jar after the render, which is what makes the encoding, the merging with cookies another integration set, and the exact form of a deletion Astro's rather than ours. Unlike session and cache, a write here is visible to a later read in the same render.

Astro.Logger

Astro.Logger.Info("built 12 products");
Astro.Logger.Warn("no price for SKU-4");
Astro.Logger.Error("feed unavailable, using cache");

Messages are collected during the render and re-emitted through Astro's own logger afterwards, so they carry their level and appear in the build output rather than on raw stderr. They surface once the component has finished rendering rather than at the moment of the call, and are still emitted if the render throws.

Unlike session, cache and CSP, this works everywhere — prerendered routes and dev included.

Outside a render

AstroContext is the per-render global, so a loader, endpoint, action or middleware cannot inject it — asking for it in a constructor fails the build, naming what to take instead. An endpoint gets one handed to it as an optional second parameter; everything else takes the individual services. See Services and startup.

Limitations

Astro.rewrite() is not available. A mid-render rewrite has no seam in the renderer: by the time C# runs, Astro has committed to rendering this route. A middleware rewrite works.

Astro.callAction() is not available, and is not needed — a C# page calls its action class directly. Doing so skips the generated validator.

Astro.Request.Content carries the request's content headers, but reading it throws — Astro has already consumed the body to route the request by the time a page renders. content-type and its siblings live on the content in .NET rather than on the request, so the content has to exist for them to arrive at all. An endpoint or middleware gets a request with its body intact.

Writing a cookie needs an on-demand route. A prerendered page is written to a file at build time and has no response to carry a Set-Cookie, so a Set or Delete there is reported and dropped rather than silently doing nothing. Reading is unaffected. In production this means experimental.serverRendering, as everything per-request does.

Session, cache and CSP reads are synchronous where Astro's are async: the state is resolved before the render and recorded mutations are replayed after it. A value written with Set is not visible to a later Get in the same render.

A response header set by a page reaches the response, as does Status, whether or not the page declares a layout — the same as an .astro page that sets them in its frontmatter.

That is worth stating because it was not always true here. Astro snapshots Astro.response.headers as the page starts producing output, so what matters is whether the code ran before that. An .astro page's frontmatter does. A .razor page's C# used to run from inside Astro's body pass, so its headers were applied to Astro's own Headers and then dropped; declaring a layout also cost the status, because the render moved into the layout's <slot />. The C# now runs at the top of the page module, which is where frontmatter runs.

A header set by a .razor component — one placed inside a page rather than being one — is still lost, because by then the snapshot has been taken. That is Astro's rule and an .astro component loses it identically.

Astro.Response.Headers is still the full Headers shape — Set replaces, Append keeps, so a header that legitimately repeats can — and it is read-your-writes within the render. Where a header has to reach the client, answer with a response of your own: an endpoint, or middleware that responds rather than continuing.