### Standard controller with filter hooks and JSON GET allowance Source: https://github.com/aspnet/aspnetwebstack Shows a typical controller with Index, GetJson (allowing GET), Create (POST), and OnResultExecuting override. Requires a repository (_repo) and Product model. JsonRequestBehavior.AllowGet permits JSON responses to GET requests. ```csharp public class ProductsController : Controller { public ActionResult Index() => View(_repo.All()); [HttpGet] public JsonResult GetJson(int id) { var model = _repo.Find(id); return Json(model, JsonRequestBehavior.AllowGet); } [HttpPost] public ActionResult Create(Product model) { if (!ModelState.IsValid) { return View(model); } _repo.Add(model); return RedirectToAction("Index"); } protected override void OnResultExecuting(ResultExecutingContext filterContext) { filterContext.Controller.ViewBag.RenderedAt = DateTime.UtcNow; base.OnResultExecuting(filterContext); } } ``` -------------------------------- ### Fully configuring a server from scratch Source: https://github.com/aspnet/aspnetwebstack Shows complete setup: routes, formatters, error policy, global filter, and hosting. Uses HttpServer for self-host/OWIN. ```csharp // 1. Configure var config = new HttpConfiguration(); config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new { id = RouteParameter.Optional }); // 2. Customize formatters and error policy config.Formatters.Remove(config.Formatters.XmlFormatter); config.Formatters.Add(new CsvMediaTypeFormatter()); config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always; // 3. Register a global filter config.Filters.Add(new RequireHttpsAttribute()); // 4. Host the server (here self-host / OWIN) using (var server = new HttpServer(config)) { // ... } ``` -------------------------------- ### Minimal hand-rolled controller example Source: https://github.com/aspnet/aspnetwebstack Shows a minimal controller that overrides ExecuteCore to write a response, and a direct call to Execute. ```csharp public sealed class PingController : ControllerBase { protected override void ExecuteCore() { Response.Output.Write("pong"); } } // Registration via existing routing + handler is framework-managed; here's the direct call: IController c = new PingController(); c.Execute(new RequestContext(new HttpContextWrapper(HttpContext.Current), new RouteData())); ``` -------------------------------- ### Typical Register-style setup Source: https://github.com/aspnet/aspnetwebstack Shows a complete Configure method using all extension methods: attribute routes, custom inline constraint, model binder, and host principal suppression. ```csharp public void Configure(HttpConfiguration config) { // Conventional + attribute routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new { id = RouteParameter.Optional }); // Custom inline constraint (e.g. "slug") var resolver = new DefaultInlineConstraintResolver(); resolver.ConstraintMap.Add("slug", typeof(SlugRouteConstraint)); config.MapHttpAttributeRoutes(resolver); // Bind a whole type via a model binder config.BindParameter(typeof(MyClaim), new MyClaimModelBinder()); // Trust only in-pipeline auth filters config.SuppressHostPrincipal(); } ``` -------------------------------- ### Example: Replacing and customizing default formatters Source: https://github.com/aspnet/aspnetwebstack Shows how to remove the XML formatter, change JSON serializer settings, and prepend a custom formatter to the collection. ```csharp var config = new HttpConfiguration(); // Remove XML entirely config.Formatters.Remove(config.Formatters.XmlFormatter); // Replace the default JSON formatter settings config.Formatters.JsonFormatter.SerializerSettings.Formatting = Formatting.Indented; // Prepend a custom formatter so it wins contention config.Formatters.Insert(0, new CsvMediaTypeFormatter()); ``` -------------------------------- ### Example: Using lookup helpers for explicit dispatch Source: https://github.com/aspnet/aspnetwebstack Demonstrates FindWriter to locate a formatter for a type and media type, and IsTypeExcludedFromValidation to check if a type is excluded from validation. ```csharp MediaTypeFormatter writer = config.Formatters.FindWriter(typeof(Product), new MediaTypeHeaderValue("application/json")); if (writer == null) { /* 406 */ } bool excluded = MediaTypeFormatterCollection.IsTypeExcludedFromValidation(typeof(byte[])); // true ``` -------------------------------- ### Basic ApiController usage with result helpers Source: https://github.com/aspnet/aspnetwebstack Shows a controller exposing both raw HttpResponseMessage and result-style actions. Get returns NotFound() for missing items or Ok(p) for found items, Post validates model state and returns CreatedAtRoute, Delete returns a raw HttpResponseMessage with NoContent status. ```csharp public class ProductsController : ApiController { private static readonly List _products = new List { new Product { Id = 1, Name = "Apples" } }; public IHttpActionResult Get(int id) { Product p = _products.FirstOrDefault(x => x.Id == id); if (p == null) { return NotFound(); // 404 } return Ok(p); // 200 + negotiated content } public IHttpActionResult Post(Product product) { if (!ModelState.IsValid) { return BadRequest(ModelState); // 400 with model-state errors } _products.Add(product); return CreatedAtRoute("DefaultApi", new { id = product.Id }, product); // 201 } public HttpResponseMessage Delete(int id) { return Request.CreateResponse(HttpStatusCode.NoContent); } } ``` -------------------------------- ### HttpRequestContext Example: Replacing Context Source: https://github.com/aspnet/aspnetwebstack Demonstrates how to replace the HttpRequestContext early in the pipeline (e.g., in a DelegatingHandler) to control error detail inclusion. ```APIDOC ## [EXAMPLE] Replacing the Context in a DelegatingHandler ### Description Demonstrates how to replace the HttpRequestContext early in the pipeline (e.g., in a DelegatingHandler) to control error detail inclusion. ### Code Example ```csharp public class DetailContextHandler : DelegatingHandler { protected override async Task SendAsync(HttpRequestMessage request, CancellationToken ct) { var ctx = request.GetRequestContext() ?? new HttpRequestContext(); ctx.IncludeErrorDetail = request.Properties.ContainsKey("DebugToken"); request.SetRequestContext(ctx); return await base.SendAsync(request, ct); } } ``` ``` -------------------------------- ### HttpRequestContext Example: Reading Context Source: https://github.com/aspnet/aspnetwebstack Demonstrates how to read the HttpRequestContext from within a controller action to access ambient request state such as IsLocal, Principal, and VirtualPathRoot. ```APIDOC ## [EXAMPLE] Reading the Context from a Controller Action ### Description Demonstrates how to read the HttpRequestContext from within a controller action to access ambient request state such as IsLocal, Principal, and VirtualPathRoot. ### Code Example ```csharp public IHttpActionResult Get(...) { HttpRequestContext ctx = Request.GetRequestContext(); bool isLocal = ctx.IsLocal; IPrincipal principal = ctx.Principal; string root = ctx.VirtualPathRoot; return Ok(new { isLocal, root }); } ``` ``` -------------------------------- ### MediaTypeMappings Property Source: https://github.com/aspnet/aspnetwebstack Gets the collection of custom media-type mappings. ```APIDOC ## MediaTypeMappings Property ### Description Gets the collection of custom media-type mappings. ### Property ```csharp public Collection MediaTypeMappings { get; } ``` ``` -------------------------------- ### Formatter Property Source: https://github.com/aspnet/aspnetwebstack Gets the formatter used to serialize the content. ```APIDOC ## Formatter Property ### Description Gets the formatter used to serialize the content. ### Method Property Get ### Endpoint `public MediaTypeFormatter Formatter { get; }` ### Response #### Success Response (200) - **Formatter** (MediaTypeFormatter) - The formatter used to serialize. ### Return Type `MediaTypeFormatter` ``` -------------------------------- ### Value Property Source: https://github.com/aspnet/aspnetwebstack Gets or sets the wrapped value. Direct assignment, no revalidation. ```APIDOC ## Value Property ### Description Gets or sets the wrapped value. Direct assignment, no revalidation. ### Method Property Get/Set ### Endpoint `public object Value { get; set; }` ### Parameters #### Request Body - **value** (object) - Required - The new value to set. ### Response #### Success Response (200) - **Value** (object) - The wrapped value. ### Return Type `object` ``` -------------------------------- ### SupportedEncodings Property Source: https://github.com/aspnet/aspnetwebstack Gets the collection of supported encodings used when reading or writing. ```APIDOC ## SupportedEncodings Property ### Description Gets the collection of supported encodings used when reading or writing. ### Property ```csharp public Collection SupportedEncodings { get; } ``` ``` -------------------------------- ### InsertRange method Source: https://github.com/aspnet/aspnetwebstack Inserts items starting at the specified index, advancing the index per element. Throws Error.ArgumentNull if items is null. ```csharp public void InsertRange(int index, IEnumerable items) ``` -------------------------------- ### CopyTo(IHttpRoute[], int) Source: https://github.com/aspnet/aspnetwebstack Copies the routes to an array, starting at a particular index. ```APIDOC ## CopyTo(IHttpRoute[], int) ### Description Copies the routes to an array, starting at a particular index. ### Method CopyTo ### Endpoint HttpRouteCollection.CopyTo(IHttpRoute[] array, int arrayIndex) ### Parameters - **array** (IHttpRoute[]) - Required - The destination array. - **arrayIndex** (int) - Required - The zero-based index in the array at which copying begins. ### Response No return value. ``` -------------------------------- ### IHttpRoute, IHttpRouteData, IHttpVirtualPathData interfaces Source: https://github.com/aspnet/aspnetwebstack Define routing contracts. IHttpRoute exposes route template, defaults, constraints, data tokens, handler, and methods to get route data and virtual path. IHttpRouteData provides the route and values. IHttpVirtualPathData provides the route and virtual path. ```csharp public interface IHttpRoute { string RouteTemplate { get; } IDictionary Defaults { get; } IDictionary Constraints { get; } IDictionary DataTokens { get; } HttpMessageHandler Handler { get; } IHttpRouteData GetRouteData(string virtualPathRoot, HttpRequestMessage request); IHttpVirtualPathData GetVirtualPath(HttpRequestMessage request, IDictionary values); } public interface IHttpRouteData { IHttpRoute Route { get; } IDictionary Values { get; } } public interface IHttpVirtualPathData { IHttpRoute Route { get; } string VirtualPath { get; set; } } ``` -------------------------------- ### SupportedMediaTypes Property Source: https://github.com/aspnet/aspnetwebstack Gets the collection of supported media types. The collection is mutable but rejects null or media ranges (e.g., */*, type/*) at insert or set time. ```APIDOC ## SupportedMediaTypes Property ### Description Gets the collection of supported media types. The collection is mutable but rejects null or media ranges (e.g., */*, type/*) at insert or set time. ### Property ```csharp public Collection SupportedMediaTypes { get; } ``` ``` -------------------------------- ### GetCorrelationId Source: https://github.com/aspnet/aspnetwebstack Gets the correlation ID for the request. Reuses Trace.CorrelationManager.ActivityId when non-empty, otherwise generates a new Guid and caches it on the request. ```APIDOC ## GetCorrelationId ### Description Gets the correlation ID for the request. Reuses Trace.CorrelationManager.ActivityId when non-empty, otherwise generates a new Guid and caches it on the request. ### Method Extension method (C#) ### Signature ```csharp public static Guid GetCorrelationId(this HttpRequestMessage request) ``` ### Parameters - **request** (HttpRequestMessage) - Required - The request message. ### Response Returns a Guid representing the correlation ID. ``` -------------------------------- ### Custom IHttpActionResult implementation with version header Source: https://github.com/aspnet/aspnetwebstack Shows how to author a custom result. The VersionedResult class creates a response with an X-Api-Version header. The controller example returns this result from a Get action. ```csharp public class VersionedResult : IHttpActionResult { private readonly HttpRequestMessage _request; private readonly object _payload; public VersionedResult(HttpRequestMessage request, object payload) { _request = request; _payload = payload; } public Task ExecuteAsync(CancellationToken cancellationToken) { var response = _request.CreateResponse(HttpStatusCode.OK, _payload); response.Headers.Add("X-Api-Version", "2"); return Task.FromResult(response); } } // In a controller: public IHttpActionResult Get() => new VersionedResult(Request, _data); ``` -------------------------------- ### HttpServer Constructor (HttpConfiguration) Source: https://github.com/aspnet/aspnetwebstack Creates an HttpServer instance with the specified configuration for direct hosting scenarios. The server can be used with an HttpClient to send requests directly into the server pipeline. ```APIDOC ## HttpServer Constructor (HttpConfiguration) ### Description Creates an HttpServer instance with the specified configuration for direct hosting scenarios. The server can be used with an HttpClient to send requests directly into the server pipeline. ### Request Example ```csharp var config = new HttpConfiguration(); config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new { id = RouteParameter.Optional }); using (var server = new HttpServer(config)) { var client = new HttpClient(server); // send requests straight into the server var response = await client.GetAsync("http://localhost/api/products/1"); } ``` ``` -------------------------------- ### GetUrlHelper Source: https://github.com/aspnet/aspnetwebstack Gets a UrlHelper for the request. ```APIDOC ## GetUrlHelper ### Description Gets a UrlHelper for the request. ### Method Extension method ### Endpoint `public static UrlHelper GetUrlHelper(this HttpRequestMessage request)` ### Parameters - `request` (HttpRequestMessage) - Required - Target request (throws on null). ### Response Returns a UrlHelper instance. ``` -------------------------------- ### Direct hosting with HttpServer Source: https://github.com/aspnet/aspnetwebstack Configures an HttpConfiguration with a default route and sends a request directly into an HttpServer using HttpClient. The server is disposed after the request. ```csharp var config = new HttpConfiguration(); config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new { id = RouteParameter.Optional }); using (var server = new HttpServer(config)) { var client = new HttpClient(server); // send requests straight into the server var response = await client.GetAsync("http://localhost/api/products/1"); } ``` -------------------------------- ### Using EnsureInitialized and discovery Source: https://github.com/aspnet/aspnetwebstack Triggers the init hook to materialize attribute routes and default services before creating the host. Useful for building help metadata. ```csharp var config = new HttpConfiguration(); config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new { id = RouteParameter.Optional }); // Trigger the init hook to materialize attribute routes and default services config.EnsureInitialized(); // After Init, GlobalConfiguration (or the OWIN helper) can begin dispatch via new HttpServer(config). ``` -------------------------------- ### TryGetValue(string, out IHttpRoute) Source: https://github.com/aspnet/aspnetwebstack Attempts to get the route with the specified name. ```APIDOC ## TryGetValue(string, out IHttpRoute) ### Description Attempts to get the route with the specified name. ### Method TryGetValue ### Endpoint HttpRouteCollection.TryGetValue(string name, out IHttpRoute route) ### Parameters - **name** (string) - Required - The route name. - **route** (out IHttpRoute) - Required - When this method returns, contains the route associated with the specified name, if found. ### Response - **bool** - true if the route was found; otherwise, false. ``` -------------------------------- ### HttpServer Constructor (HttpMessageHandler) Source: https://github.com/aspnet/aspnetwebstack Creates an HttpServer instance with a custom dispatcher handler that short-circuits routing. The provided handler receives all requests directly. ```APIDOC ## HttpServer Constructor (HttpMessageHandler) ### Description Creates an HttpServer instance with a custom dispatcher handler that short-circuits routing. The provided handler receives all requests directly. ### Request Example ```csharp public sealed class GreeterDispatcher : HttpMessageHandler { protected override Task SendAsync(HttpRequestMessage request, CancellationToken ct) { var msg = "Hello from a custom dispatcher"; var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(msg, Encoding.UTF8, "text/plain") }; response.RequestMessage = request; return Task.FromResult(response); } } var server = new HttpServer(new GreeterDispatcher()); ``` ``` -------------------------------- ### ObjectType Property Source: https://github.com/aspnet/aspnetwebstack Gets the declared object type of the content. ```APIDOC ## ObjectType Property ### Description Gets the declared object type of the content. ### Method Property Get ### Endpoint `public Type ObjectType { get; }` ### Response #### Success Response (200) - **ObjectType** (Type) - The declared object type. ### Return Type `Type` ``` -------------------------------- ### WebApiConfig.Register bootstrap with content negotiation and error detail settings Source: https://github.com/aspnet/aspnetwebstack Configures attribute and conventional routes, replaces the default IContentNegotiator with DefaultContentNegotiator(excludeMatchOnTypeOnly: true) to return 406 when only type-only matching is possible, sets IncludeErrorDetailPolicy to Always (not for production), and replaces IExceptionHandler with a custom handler. Host via new HttpServer(config) in self-host or GlobalConfiguration.Configure(WebApiConfig.Register). ```csharp public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Attribute and conventional routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional }); // Replace the default negotiator: 406 when only type-matching possible config.Services.Replace(typeof(IContentNegotiator), new DefaultContentNegotiator(excludeMatchOnTypeOnly: true)); // Always show developer error details (do not ship this in production) config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always; // Replace exception handling config.Services.Replace(typeof(IExceptionHandler), new MyExceptionHandler()); } } // Host: new HttpServer(config) inside detached/self-host, or GlobalConfiguration.Configure(WebApiConfig.Register). ``` -------------------------------- ### RequiredMemberSelector Property Source: https://github.com/aspnet/aspnetwebstack Gets or sets the selector that determines required members. Assigned by the HttpConfiguration initializer when unset. ```APIDOC ## RequiredMemberSelector Property ### Description Gets or sets the selector that determines required members. Assigned by the HttpConfiguration initializer when unset. ### Property ```csharp public IRequiredMemberSelector RequiredMemberSelector { get; set; } ``` ``` -------------------------------- ### HttpConfiguration() Source: https://github.com/aspnet/aspnetwebstack Initializes a new instance of the HttpConfiguration class with a default route collection and default services. ```APIDOC ## [CONSTRUCTOR] HttpConfiguration() ### Description Initializes a new instance of the HttpConfiguration class with a default route collection and default services. ### Method Constructor ### Signature ```csharp public HttpConfiguration() ``` ### Parameters None ### Remarks Creates a route collection with `VirtualPathRoot` `/`. The instance is wired with a fresh `DefaultServices`, a `MediaTypeFormatterCollection` primed with a `JQueryMvcFormUrlEncodedFormatter` (added to the base Json/Xml/FormUrlEncoded set), and the default parameter binding rules from `DefaultActionValueBinder.GetDefaultParameterBinders()`. ``` -------------------------------- ### CopyTo(KeyValuePair[], int) Source: https://github.com/aspnet/aspnetwebstack Copies the routes as key-value pairs to an array, starting at a particular index. ```APIDOC ## CopyTo(KeyValuePair[], int) ### Description Copies the routes as key-value pairs to an array, starting at a particular index. ### Method CopyTo ### Endpoint HttpRouteCollection.CopyTo(KeyValuePair[] array, int arrayIndex) ### Parameters - **array** (KeyValuePair[]) - Required - The destination array. - **arrayIndex** (int) - Required - The zero-based index in the array at which copying begins. ### Response No return value. ``` -------------------------------- ### Execute method implementation Source: https://github.com/aspnet/aspnetwebstack Implements IController.Execute with validation and initialization steps. ```csharp protected virtual void Execute(RequestContext requestContext) void IController.Execute(RequestContext requestContext) // explicit — calls Execute ``` -------------------------------- ### EnsureInitialized method signature Source: https://github.com/aspnet/aspnetwebstack Public method that runs the Initializer exactly once. Subsequent calls are no-ops due to the _initialized guard. Configuration is immutable after this point. ```csharp public void EnsureInitialized() ``` -------------------------------- ### MediaTypeFormatter Copy Constructor Source: https://github.com/aspnet/aspnetwebstack Initializes a new instance of the MediaTypeFormatter class by copying the settings from an existing formatter. Throws an exception if the provided formatter is null. ```APIDOC ## MediaTypeFormatter(MediaTypeFormatter formatter) ### Description Initializes a new instance of the MediaTypeFormatter class by copying the settings from an existing formatter. Throws an exception if the provided formatter is null. ### Method Constructor ### Parameters - **formatter** (MediaTypeFormatter) - Required - The formatter to copy from. ### Signature ```csharp protected MediaTypeFormatter(MediaTypeFormatter formatter) ``` ``` -------------------------------- ### MaxHttpCollectionKeys Property Source: https://github.com/aspnet/aspnetwebstack Gets or sets the maximum number of keys stored in a NameValueCollection during form parsing. The setter requires a value greater than or equal to 1. ```APIDOC ## MaxHttpCollectionKeys Property ### Description Gets or sets the maximum number of keys stored in a NameValueCollection during form parsing. The setter requires a value greater than or equal to 1. ### Property ```csharp public static int MaxHttpCollectionKeys { get; set; } ``` ### Remarks - Default value is 1000. - The setter throws an exception if the value is less than 1. ``` -------------------------------- ### Building a response manually with a chosen media type Source: https://github.com/aspnet/aspnetwebstack Creates an ObjectContent with a JsonMediaTypeFormatter and a specific media type, then assigns it to an HttpResponseMessage. ```csharp var formatter = new JsonMediaTypeFormatter(); var content = new ObjectContent(product, formatter, "application/json"); var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = content }; ``` -------------------------------- ### Initialize(RequestContext) Source: https://github.com/aspnet/aspnetwebstack Initializes the controller by setting the ControllerContext property to a new ControllerContext instance created from the provided request context and the current controller instance. ```APIDOC ## [PROTECTED] Initialize(RequestContext) ### Description Initializes the controller by setting the ControllerContext property to a new ControllerContext instance created from the provided request context and the current controller instance. ### Method protected virtual void Initialize(RequestContext requestContext) ### Parameters #### Path Parameters - **requestContext** (RequestContext) - Required - The request/route context. ### Response #### Success Response (200) - **void** - No return value. ``` -------------------------------- ### HttpRoute Constructor Source: https://github.com/aspnet/aspnetwebstack Initializes a new instance of the HttpRoute class with the specified route template, defaults, constraints, data tokens, and handler. The route template is parsed at construction time. ```APIDOC ## [CONSTRUCTOR] HttpRoute ### Description Initializes a new instance of the HttpRoute class with the specified route template, defaults, constraints, data tokens, and handler. The route template is parsed at construction time. ### Parameters - `routeTemplate` (string) - Optional - Route template; parsed at construction. Default: `String.Empty` - `defaults` (HttpRouteValueDictionary) - Optional - Default values. Default: `null` - `constraints` (HttpRouteValueDictionary) - Optional - Constraint rules. Default: `null` - `dataTokens` (HttpRouteValueDictionary) - Optional - Data tokens. Default: `null` - `handler` (HttpMessageHandler) - Optional - Terminal handler. Default: `null` ### Throws - `RouteParser` parse exception - invalid route template at construction. - `Error.InvalidOperation(Route_ValidationMustBeStringOrCustomConstraint)` - non-string, non-`IHttpRouteConstraint` constraint. ### Request Example ```csharp var route = new HttpRoute("api/products/{id}", new HttpRouteValueDictionary { { "id", RouteParameter.Optional } }); ``` ``` -------------------------------- ### Abstract and virtual hooks Source: https://github.com/aspnet/aspnetwebstack Defines the abstract ExecuteCore and virtual Initialize methods. ```csharp protected abstract void ExecuteCore(); protected virtual void Initialize(RequestContext requestContext) ``` -------------------------------- ### HttpRoute Constructors Source: https://github.com/aspnet/aspnetwebstack Initializes a new instance of the HttpRoute class. Multiple overloads allow specifying the route template, defaults, constraints, data tokens, and an optional HTTP message handler. ```APIDOC ## [CONSTRUCTOR] HttpRoute() ### Description Initializes a new instance of the HttpRoute class with default values. ### Method Constructor ### Parameters None ### Response No return value. ## [CONSTRUCTOR] HttpRoute(string routeTemplate) ### Description Initializes a new instance of the HttpRoute class with the specified route template. ### Method Constructor ### Parameters - **routeTemplate** (string) - Required - The route template for the route. ### Response No return value. ## [CONSTRUCTOR] HttpRoute(string routeTemplate, HttpRouteValueDictionary defaults) ### Description Initializes a new instance of the HttpRoute class with the specified route template and default values. ### Method Constructor ### Parameters - **routeTemplate** (string) - Required - The route template for the route. - **defaults** (HttpRouteValueDictionary) - Optional - The default values for the route. ### Response No return value. ## [CONSTRUCTOR] HttpRoute(string routeTemplate, HttpRouteValueDictionary defaults, HttpRouteValueDictionary constraints) ### Description Initializes a new instance of the HttpRoute class with the specified route template, defaults, and constraints. ### Method Constructor ### Parameters - **routeTemplate** (string) - Required - The route template for the route. - **defaults** (HttpRouteValueDictionary) - Optional - The default values for the route. - **constraints** (HttpRouteValueDictionary) - Optional - The constraints for the route. ### Response No return value. ## [CONSTRUCTOR] HttpRoute(string routeTemplate, HttpRouteValueDictionary defaults, HttpRouteValueDictionary constraints, HttpRouteValueDictionary dataTokens) ### Description Initializes a new instance of the HttpRoute class with the specified route template, defaults, constraints, and data tokens. ### Method Constructor ### Parameters - **routeTemplate** (string) - Required - The route template for the route. - **defaults** (HttpRouteValueDictionary) - Optional - The default values for the route. - **constraints** (HttpRouteValueDictionary) - Optional - The constraints for the route. - **dataTokens** (HttpRouteValueDictionary) - Optional - The data tokens for the route. ### Response No return value. ## [CONSTRUCTOR] HttpRoute(string routeTemplate, HttpRouteValueDictionary defaults, HttpRouteValueDictionary constraints, HttpRouteValueDictionary dataTokens, HttpMessageHandler handler) ### Description Initializes a new instance of the HttpRoute class with the specified route template, defaults, constraints, data tokens, and HTTP message handler. ### Method Constructor ### Parameters - **routeTemplate** (string) - Required - The route template for the route. - **defaults** (HttpRouteValueDictionary) - Optional - The default values for the route. - **constraints** (HttpRouteValueDictionary) - Optional - The constraints for the route. - **dataTokens** (HttpRouteValueDictionary) - Optional - The data tokens for the route. - **handler** (HttpMessageHandler) - Optional - The HTTP message handler for the route. ### Response No return value. ``` -------------------------------- ### MapHttpAttributeRoutes overloads Source: https://github.com/aspnet/aspnetwebstack Discovers attribute-routed controllers and builds direct routes. Defaults to DefaultInlineConstraintResolver and DefaultDirectRouteProvider. Throws ArgumentNullException on null arguments. ```csharp public static void MapHttpAttributeRoutes(this HttpConfiguration configuration) ``` ```csharp public static void MapHttpAttributeRoutes(this HttpConfiguration configuration, IInlineConstraintResolver constraintResolver) ``` ```csharp public static void MapHttpAttributeRoutes(this HttpConfiguration configuration, IDirectRouteProvider directRouteProvider) ``` ```csharp public static void MapHttpAttributeRoutes(this HttpConfiguration configuration, IInlineConstraintResolver constraintResolver, IDirectRouteProvider directRouteProvider) ``` -------------------------------- ### Constructors for HttpRouteCollection Source: https://github.com/aspnet/aspnetwebstack Provides two constructors. The parameterless one defaults virtualPathRoot to "/". The string constructor throws Error.ArgumentNull on null and validates the root as an absolute/relative URI. ```csharp public HttpRouteCollection() public HttpRouteCollection(string virtualPathRoot) ``` -------------------------------- ### Custom exception handler example Source: https://github.com/aspnet/aspnetwebstack Custom handler that converts exceptions into an HTTP 500 error response with a message. Overrides the Handle method to set the result to a ResponseMessageResult. ```csharp // Custom handler example public class MyExceptionHandler : ExceptionHandler { public override void Handle(ExceptionHandlerContext context) { context.Result = new ResponseMessageResult( context.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "A server error occurred.")); } } ``` -------------------------------- ### Protected virtual helper methods Source: https://github.com/aspnet/aspnetwebstack Overridable helper methods used during negotiation. They handle matching against media-type mappings, Accept headers, request media type, and type, as well as sorting and selection logic. ```csharp protected virtual Collection ComputeFormatterMatches(Type type, HttpRequestMessage request, IEnumerable formatters) protected virtual MediaTypeFormatterMatch SelectResponseMediaTypeFormatter(ICollection matches) protected virtual Encoding SelectResponseCharacterEncoding(HttpRequestMessage request, MediaTypeFormatter formatter) protected virtual MediaTypeFormatterMatch MatchMediaTypeMapping(HttpRequestMessage request, MediaTypeFormatter formatter) protected virtual MediaTypeFormatterMatch MatchAcceptHeader(IEnumerable sortedAcceptValues, MediaTypeFormatter formatter) protected virtual MediaTypeFormatterMatch MatchRequestMediaType(HttpRequestMessage request, MediaTypeFormatter formatter) protected virtual bool ShouldMatchOnType(IEnumerable sortedAcceptValues) protected virtual MediaTypeFormatterMatch MatchType(Type type, MediaTypeFormatter formatter) protected virtual IEnumerable SortMediaTypeWithQualityHeaderValuesByQFactor(ICollection headerValues) protected virtual IEnumerable SortStringWithQualityHeaderValuesByQFactor(ICollection headerValues) protected virtual MediaTypeFormatterMatch UpdateBestMatch(MediaTypeFormatterMatch current, MediaTypeFormatterMatch potentialReplacement) ``` -------------------------------- ### Drive negotiation directly with DefaultContentNegotiator Source: https://github.com/aspnet/aspnetwebstack Use this to invoke negotiation manually, for example in a custom result. It returns a ContentNegotiationResult or null; if null, respond with 406 Not Acceptable. The result's Formatter and MediaType are used to create an ObjectContent. ```csharp var negotiator = new DefaultContentNegotiator(); ContentNegotiationResult result = negotiator.Negotiate( typeof(Product), request, config.Formatters); if (result == null) { // No acceptable formatter -> respond 406 return request.CreateResponse(HttpStatusCode.NotAcceptable); } var content = new ObjectContent(product, result.Formatter, result.MediaType); return new HttpResponseMessage { Content = content }; ``` -------------------------------- ### Match* methods Source: https://github.com/aspnet/aspnetwebstack Match methods evaluate whether a formatter matches the request criteria. Return a MediaTypeFormatterMatch. ```APIDOC ## Match* methods ### Description Match methods evaluate whether a formatter matches the request criteria. Return a MediaTypeFormatterMatch. ### Parameters - `type` (Type) - Required - Target type to serialize. - `request` (HttpRequestMessage) - Required - Request used for headers/mappings. - `formatters` (IEnumerable) - Required - Candidate formatters. - `sortedAcceptValues` (IEnumerable) - Required - Pre-sorted Accept values. - `matches` / `matchList` (ICollection) - Required - Candidate match set. - `headerValues` (ICollection / ICollection) - Required - Header values to sort. - `current` / `potentialReplacement` (MediaTypeFormatterMatch) - Required - Best-match evaluation inputs. ### Return Type `MediaTypeFormatterMatch` ### Throws - `Error.ArgumentNull("type"/"request"/"formatters"/...)` - null argument passed to public/protected methods. ``` -------------------------------- ### Explicit model updates and validation with error handling Source: https://github.com/aspnet/aspnetwebstack Demonstrates TryUpdateModel with a whitelist and value provider, then UpdateModel and ValidateModel inside a try-catch. UpdateModel throws InvalidOperationException on binding failure; ValidateModel throws if the model is invalid. Requires a repository (_repo) and a Product model. ```csharp [HttpPost] public ActionResult Edit(int id, FormCollection form) { var model = _repo.Find(id); if (!TryUpdateModel(model, "Product", new[] { "Name", "Price" }, valueProvider: ValueProvider)) { return View(model); // ModelState already populated } try { UpdateModel(model); // throws if binding fails ValidateModel(model); // throws InvalidOperationException if invalid _repo.Save(model); return RedirectToAction("Index"); } catch (InvalidOperationException) { return View(model); } } ``` -------------------------------- ### Custom dispatcher with GreeterDispatcher Source: https://github.com/aspnet/aspnetwebstack Defines a custom HttpMessageHandler that short-circuits routing and returns a fixed response. The handler is passed to an HttpServer constructor. ```csharp public sealed class GreeterDispatcher : HttpMessageHandler { protected override Task SendAsync(HttpRequestMessage request, CancellationToken ct) { var msg = "Hello from a custom dispatcher"; var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(msg, Encoding.UTF8, "text/plain") }; response.RequestMessage = request; return Task.FromResult(response); } } var server = new HttpServer(new GreeterDispatcher()); ``` -------------------------------- ### EnsureInitialized Source: https://github.com/aspnet/aspnetwebstack Runs the Initializer delegate exactly once on the configuration instance. Subsequent calls are no-ops because the _initialized guard is already set, and the configuration is considered immutable after this point. ```APIDOC ## EnsureInitialized ### Description Runs `Initializer(this)` exactly once (subsequent calls are no-ops because the `_initialized` guard is already set). The configuration is considered immutable after this point. ### Method EnsureInitialized ### Signature ```csharp public void EnsureInitialized() ``` ### Return Type `void` ### Example ```csharp var config = new HttpConfiguration(); config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new { id = RouteParameter.Optional }); // Trigger the init hook to materialize attribute routes and default services config.EnsureInitialized(); // After Init, GlobalConfiguration (or the OWIN helper) can begin dispatch via new HttpServer(config). ``` ``` -------------------------------- ### Add Source: https://github.com/aspnet/aspnetwebstack Adds a route to the collection. Returns void. ```APIDOC ## Add ### Description Adds a route to the collection. Returns void. ### Parameters - `name` (string) - Required - Route name key. - `routeTemplate` (string) - Required - Route pattern (e.g. `"api/{controller}/{id}"`). - `defaults` (object / IDictionary) - Optional - Default route values. - `constraints` (object / IDictionary) - Optional - Constraint expressions. - `dataTokens` (IDictionary) - Optional - Data tokens / route metadata. - `handler` (HttpMessageHandler) - Optional - Terminal handler for this route. ### Return Type Returns void. ``` -------------------------------- ### BindParameter method signature Source: https://github.com/aspnet/aspnetwebstack Registers a SimpleModelBinderProvider for the given type and inserts a parameter binding rule. Throws Error.ArgumentNull on null arguments. ```csharp public static void BindParameter(this HttpConfiguration configuration, Type type, IModelBinder binder) ``` -------------------------------- ### Reading ambient state in a normal MVC controller Source: https://github.com/aspnet/aspnetwebstack Shows how to use ViewBag, ViewData, and TempData inside a controller that inherits ControllerBase. ```csharp public class HomeController : Controller { public ActionResult Index() { ViewBag.Message = "Welcome"; ViewData["now"] = DateTime.UtcNow; TempData["referrer"] = Request.UrlReferrer?.AbsoluteUri; return View(); } } ``` -------------------------------- ### MediaTypeFormatterMatch class Source: https://github.com/aspnet/aspnetwebstack Constructor throws on null formatter; defaults Quality to FormattingUtilities.Match and MediaType to application/octet-stream when absent. ```csharp public class MediaTypeFormatterMatch { public MediaTypeFormatter Formatter { get; private set; } public MediaTypeHeaderValue MediaType { get; private set; } public double Quality { get; private set; } public MediaTypeFormatterMatchRanking Ranking { get; private set; } } ``` -------------------------------- ### ObjectContent Constructor Source: https://github.com/aspnet/aspnetwebstack Initializes a new instance of the ObjectContent class with a specified value and formatter. Validates that the formatter can write the type and that the value is compatible with the type. ```APIDOC ## ObjectContent Constructor ### Description Initializes a new instance of the ObjectContent class with a specified value and formatter. Validates that the formatter can write the type and that the value is compatible with the type. ### Method Constructor ### Endpoint `public ObjectContent(T value, MediaTypeFormatter formatter)` `public ObjectContent(T value, MediaTypeFormatter formatter, string mediaType)` `public ObjectContent(T value, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType)` ### Parameters #### Path Parameters - **value** (T) - Required; null permitted for reference/nullable types - The wrapped value. - **formatter** (MediaTypeFormatter) - Required - Formatter used to serialize. - **mediaType** (string / MediaTypeHeaderValue) - Optional (may be null) - Authoritative Content-Type (else formatter default). ### Response #### Success Response (200) - **ObjectContent** - The created ObjectContent instance. ### Throws - `Error.ArgumentNull("type"/"formatter")` - null type or formatter. - `Error.InvalidOperation(FormatterCannotWriteType)` - formatter cannot write the object type. - `Error.InvalidOperation(CannotUseNullValueType)` - null value on a non-nullable value type. - `Error.Argument("value", ObjectAndTypeDisagree)` - non-null value not assignable to `type`. - `Error.ArgumentNull("mediaType")` (via `BuildHeaderValue`) - invalid media type string. ### Request Example ```csharp var formatter = new JsonMediaTypeFormatter(); var content = new ObjectContent(product, formatter, "application/json"); var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = content }; ``` ``` -------------------------------- ### Validate Source: https://github.com/aspnet/aspnetwebstack Runs the registered IBodyModelValidator against the entity and adds results to ModelState. Throws InvalidOperationException if Configuration is null. ```APIDOC ## Validate ### Description Runs the registered `IBodyModelValidator` against the entity and adds results to `ModelState`. Throws `InvalidOperationException` if `Configuration` is null. ### Method Validate ### Signatures ```csharp public void Validate(TEntity entity) public void Validate(TEntity entity, string keyPrefix) ``` ### Parameters - **entity** (TEntity) - Required - The entity to validate. - **keyPrefix** (string) - Optional - The key prefix for validation errors. ### Returns - **void** - No return value. ``` -------------------------------- ### BindParameter Source: https://github.com/aspnet/aspnetwebstack Registers a SimpleModelBinderProvider for the specified type and inserts a parameter binding rule so parameters of that type are bound with the given model binder. Throws Error.ArgumentNull if any argument is null. ```APIDOC ## BindParameter ### Description Registers a `SimpleModelBinderProvider(type, binder)` at position 0 of the `ModelBinderProvider` service list and inserts a rule into `ParameterBindingRules` so parameters of `type` are bound with that binder (rather than by formatters). Throws `Error.ArgumentNull` on null `configuration`/`type`/`binder`. ### Method Extension method (C#) ### Signature ```csharp public static void BindParameter(this HttpConfiguration configuration, Type type, IModelBinder binder) ``` ### Parameters - `configuration` (HttpConfiguration) - Required - Target configuration. - `type` (Type) - Required - Parameter type to bind with the model binder. - `binder` (IModelBinder) - Required - The model binder to apply. ### Return Type void ### Throws - `Error.ArgumentNull` - If `configuration`, `type`, or `binder` is null. ### Example ```csharp config.BindParameter(typeof(MyClaim), new MyClaimModelBinder()); ``` ``` -------------------------------- ### Negotiate Method Source: https://github.com/aspnet/aspnetwebstack Performs content negotiation to select the best formatter and media type for the given type, request, and formatters. Returns a ContentNegotiationResult or null if no match is found. ```APIDOC ## Negotiate Method ### Description Performs content negotiation to select the best formatter and media type for the given type, request, and formatters. Returns a ContentNegotiationResult or null if no match is found. ### Method Negotiate ### Signature ```csharp public virtual ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request, IEnumerable formatters) ``` ### Parameters - `type` (Type) - Required - The type to be serialized. - `request` (HttpRequestMessage) - Required - The HTTP request message. - `formatters` (IEnumerable) - Required - The collection of formatters to consider. ### Returns - `ContentNegotiationResult` - The result containing the best formatter and media type, or `null` if no match exists. ### Exceptions - Throws `Error.ArgumentNull` on null `type`/`request`/`formatters`. ### Remarks The method computes formatter matches, selects the best match by precedence, and picks the character encoding. The match's `MediaType.CharSet` is set accordingly. `GetPerRequestFormatterInstance` may be invoked on the winning formatter. ``` -------------------------------- ### HttpConfiguration(HttpRouteCollection routes) Source: https://github.com/aspnet/aspnetwebstack Initializes a new instance of the HttpConfiguration class with the specified route collection. ```APIDOC ## [CONSTRUCTOR] HttpConfiguration(HttpRouteCollection routes) ### Description Initializes a new instance of the HttpConfiguration class with the specified route collection. ### Method Constructor ### Signature ```csharp public HttpConfiguration(HttpRouteCollection routes) ``` ### Parameters - **routes** (HttpRouteCollection) - Required - The route collection to use. Throws `Error.ArgumentNull("routes")` if null. ### Remarks The instance is wired with a fresh `DefaultServices`, a `MediaTypeFormatterCollection` primed with a `JQueryMvcFormUrlEncodedFormatter` (added to the base Json/Xml/FormUrlEncoded set), and the default parameter binding rules from `DefaultActionValueBinder.GetDefaultParameterBinders()`. ``` -------------------------------- ### Constructors for MediaTypeFormatterCollection Source: https://github.com/aspnet/aspnetwebstack Provides the parameterless and enumerable constructors. The parameterless constructor seeds the collection with default formatters (Json, Xml, FormUrlEncoded). The enumerable constructor throws on null or null elements. ```csharp public MediaTypeFormatterCollection() public MediaTypeFormatterCollection(IEnumerable formatters) ``` -------------------------------- ### HttpControllerContext Source: https://github.com/aspnet/aspnetwebstack Provides context for an HTTP controller operation, including configuration, request, and route data. Multiple constructors are available, and some properties throw on null setters. ```APIDOC ## HttpControllerContext ### Description Provides context for an HTTP controller operation, including configuration, request, and route data. Multiple constructors are available, and some properties throw on null setters. ### Constructors - `HttpControllerContext()` - Initializes with empty request context. - `HttpControllerContext(HttpRequestContext requestContext, HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, IHttpController controller)` - All arguments required; null throws Error.ArgumentNull. - `HttpControllerContext(HttpConfiguration configuration, IHttpRouteData routeData, HttpRequestMessage request)` - Initializes with configuration, route data, and request. ### Properties - **Configuration** (HttpConfiguration) - Gets or sets the configuration. Setter throws on null. - **ControllerDescriptor** (HttpControllerDescriptor) - Gets or sets the controller descriptor. - **Controller** (IHttpController) - Gets or sets the controller. - **Request** (HttpRequestMessage) - Gets or sets the request. Setter throws on null. - **RequestContext** (HttpRequestContext) - Gets or sets the request context. Setter throws on null. - **RouteData** (IHttpRouteData) - Gets or sets the route data. Forwards to RequestContext. - **Url** (UrlHelper) - Gets or sets the URL helper. Forwards to RequestContext. ``` -------------------------------- ### TryComputeLength Method Source: https://github.com/aspnet/aspnetwebstack Attempts to compute the content length. Always returns false and sets length to -1 (non-buffered). ```APIDOC ## TryComputeLength Method ### Description Attempts to compute the content length. Always returns false and sets length to -1 (non-buffered). ### Method Protected Override ### Endpoint `protected override bool TryComputeLength(out long length)` ### Parameters #### Path Parameters - **length** (long) - Required - The computed length (always set to -1). ### Response #### Success Response (200) - **bool** - Always false. ### Return Type `bool` (always `false`) ``` -------------------------------- ### Registering and using the formatter Source: https://github.com/aspnet/aspnetwebstack Shows how to register the custom formatter in the configuration and use it in an API action. Content negotiation will select the CSV formatter when the request's Accept header is text/csv. ```csharp config.Formatters.Add(new CsvMediaTypeFormatter()); public IHttpActionResult Get() { // Content negotiation will pick the CSV formatter when Accept: text/csv return Ok(new ReportRow[] { new ReportRow { Id = 1, Name = "A" } }); } ``` -------------------------------- ### ContentNegotiationResult class Source: https://github.com/aspnet/aspnetwebstack Returned by IContentNegotiator.Negotiate. The Formatter setter throws on null. ```csharp public class ContentNegotiationResult { public MediaTypeFormatter Formatter { get; set; } // setter throws on null public MediaTypeHeaderValue MediaType { get; set; } } ``` -------------------------------- ### HttpRequestContext constructor Source: https://github.com/aspnet/aspnetwebstack Parameterless constructor available to support breakpoint placement on construction. ```csharp public HttpRequestContext() ```