liveBook · Manning

DefaultHttpContext

As explained in ASP.NET Core in Action, 3e

DefaultHttpContext is an ASP.NET Core implementation of HttpContext that provides default request and response state for an HTTP request.

DefaultHttpContext is an ASP.NET Core implementation of HttpContext for unit-testing custom middleware. Create one, configure its request, invoke the middleware, and inspect the resulting behavior. section 36.1

A typical middleware test uses it to:

  • Set Request.Path to exercise a matching or nonmatching request. section 36.1
  • Pass the context to middleware and verify that the next RequestDelegate was called when the path does not match. section 36.1
  • Replace Response.Body with a MemoryStream when the test must read response content; the default Stream.Null discards it. section 36.5 section 36.1

Testing a ping response

Create a DefaultHttpContext, assign a MemoryStream to Response.Body, set Request.Path to "/ping", invoke the middleware, then rewind and read the stream to verify the response body contains "pong". The same test can check the status code and text/plain content type. section 36.1

How ASP.NET Core in Action, 3e covers it

How deep it goes
Defines context setup and response capture, but does not cover full application integration behavior.
Examples
Uses /ping and /somethingelse requests to test response generation and next-delegate invocation.
What it assumes
Assumes familiarity with middleware, HttpContext, RequestDelegate, and asynchronous C# tests.
What you can do after
Build isolated middleware tests that configure requests and inspect response state or captured body content.
How it connects
Connects HttpContext, RequestDelegate, middleware, response bodies, and MemoryStream.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.