liveBook · Manning

Code on demand

As explained in Building Web APIs with ASP.NET Core

Code on demand is a REST constraint allowing a server to send executable code that extends client behavior.

Code on demand (COD) is an optional REST constraint: a server returns executable code that gives a client additional behavior. A browser, for example, can download JavaScript that renders an interface or makes further HTTP requests. COD can improve performance and scalability, but executing supplied code reduces visibility and brings security risks. section 1.1.4 section 3.1.5

An API that primarily returns JSON may have little reason to use COD. For a concrete exception, a `/cod/test` endpoint can return HTML that checks whether the calling browser runs JavaScript and displays the result. section 3.1.5

The test endpoint has three parts:

  • Map a GET request to `/cod/test` and return the response as `text/html`. section 3.1.5
  • Include a `<script>` that shows an alert with server and client UTC times when JavaScript runs. section 3.1.5
  • Include a `<noscript>` message for a browser with JavaScript disabled; apply the `AnyOrigin` CORS policy and prevent response caching with `NoStore = true`. section 3.1.5
app.MapGet("/cod/test",
   [EnableCors("AnyOrigin")]
   [ResponseCache(NoStore = true)] () =>
   Results.Text("<script>" +
       "window.alert('Your client supports JavaScript!" +
       "\\r\\n\\r\\n" +
       $"Server time (UTC): {DateTime.UtcNow.ToString("o")}" +
       "\\r\\n" +
       "Client time (UTC): ' + new Date().toISOString());" +
       "</script>" +
       "<noscript>Your client does not support JavaScript</noscript>",
       "text/html"));

The Minimal API listing puts the route, response content, CORS policy, and no-store setting together. section 3.1.5

Open the route with JavaScript enabled to check for the alert, then disable JavaScript and reload it to check for the text fallback. This demonstrates client-executed code without making COD a requirement for every RESTful API. section 1.1.4 section 3.1.5

How Building Web APIs with ASP.NET Core covers it

How deep it goes
Defines the constraint and walks through a Minimal API example, stopping short of a broader application implementation.
Examples
Demonstrates a `/cod/test` HTML response with a JavaScript alert and a `<noscript>` fallback.
What it assumes
Assumes a running Minimal API project while defining COD before applying it to a browser test.
What you can do after
Build it from scratch as a small ASP.NET Core Minimal API endpoint and verify both browser outcomes.
How it connects
Connects COD to REST constraints, JavaScript, HTTP requests, CORS, and response caching.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Building Web APIs with ASP.NET Core. The section links point to the parts of the book it draws on.