"
 
 
 
ASP.NET (snapshot 2017) Microsoft documentation and samples

Migrating HTTP handlers and modules to ASP.NET Core middleware

By Matt Perdeck

This article shows how to migrate existing ASP.NET HTTP modules and handlers from system.webserver to ASP.NET Core middleware.

Modules and handlers revisited

Before proceeding to ASP.NET Core middleware, let’s first recap how HTTP modules and handlers work:

Modules Handler
Modules Handler

Handlers are:

Modules are:

The order in which modules process incoming requests is determined by:

  1. The application life cycle, which is a series events fired by ASP.NET: BeginRequest, AuthenticateRequest, etc. Each module can create a handler for one or more events.

  2. For the same event, the order in which they are configured in Web.config.

In addition to modules, you can add handlers for the life cycle events to your Global.asax.cs file. These handlers run after the handlers in the configured modules.

From handlers and modules to middleware

Middleware are simpler than HTTP modules and handlers:

Middleware are very similar to modules:

Middleware and modules are processed in a different order:

Middleware
Middleware

Note how in the image above, the authentication middleware short-circuited the request.

Migrating module code to middleware

An existing HTTP module will look similar to this:

[!code-csharpMain]

   1:  // ASP.NET 4 module
   2:   
   3:  using System;
   4:  using System.Web;
   5:   
   6:  namespace MyApp.Modules
   7:  {
   8:      public class MyModule : IHttpModule
   9:      {
  10:          public void Dispose()
  11:          {
  12:          }
  13:   
  14:          public void Init(HttpApplication application)
  15:          {
  16:              application.BeginRequest += (new EventHandler(this.Application_BeginRequest));
  17:              application.EndRequest += (new EventHandler(this.Application_EndRequest));
  18:          }
  19:   
  20:          private void Application_BeginRequest(Object source, EventArgs e)
  21:          {
  22:              HttpContext context = ((HttpApplication)source).Context;
  23:   
  24:              // Do something with context near the beginning of request processing.
  25:          }
  26:   
  27:          private void Application_EndRequest(Object source, EventArgs e)
  28:          {
  29:              HttpContext context = ((HttpApplication)source).Context;
  30:   
  31:              // Do something with context near the end of request processing.
  32:          }
  33:      }
  34:  }

As shown in the Middleware page, an ASP.NET Core middleware is a class that exposes an Invoke method taking an HttpContext and returning a Task. Your new middleware will look like this:

[!code-csharpMain]

   1:  // ASP.NET Core middleware
   2:   
   3:  using Microsoft.AspNetCore.Builder;
   4:  using Microsoft.AspNetCore.Http;
   5:  using System.Threading.Tasks;
   6:   
   7:  namespace MyApp.Middleware
   8:  {
   9:      public class MyMiddleware
  10:      {
  11:          private readonly RequestDelegate _next;
  12:   
  13:          public MyMiddleware(RequestDelegate next)
  14:          {
  15:              _next = next;
  16:          }
  17:   
  18:          public async Task Invoke(HttpContext context)
  19:          {
  20:              // Do something with context near the beginning of request processing.
  21:   
  22:              await _next.Invoke(context);
  23:   
  24:              // Clean up.
  25:          }
  26:      }
  27:   
  28:      public static class MyMiddlewareExtensions
  29:      {
  30:          public static IApplicationBuilder UseMyMiddleware(this IApplicationBuilder builder)
  31:          {
  32:              return builder.UseMiddleware<MyMiddleware>();
  33:          }
  34:      }
  35:  }

The above middleware template was taken from the section on writing middleware.

The MyMiddlewareExtensions helper class makes it easier to configure your middleware in your Startup class. The UseMyMiddleware method adds your middleware class to the request pipeline. Services required by the middleware get injected in the middleware’s constructor.

Your module might terminate a request, for example if the user is not authorized:

[!code-csharpMain]

   1:  using System;
   2:  using System.Web;
   3:   
   4:  namespace MyApp.Modules
   5:  {
   6:      public class MyTerminatingModule : IHttpModule
   7:      {
   8:          public void Dispose()
   9:          {
  10:          }
  11:   
  12:          public void Init(HttpApplication application)
  13:          {
  14:              application.BeginRequest += (new EventHandler(this.Application_BeginRequest));
  15:              application.EndRequest += (new EventHandler(this.Application_EndRequest));
  16:          }
  17:   
  18:          #region snippet_Terminate
  19:          // ASP.NET 4 module that may terminate the request
  20:   
  21:          private void Application_BeginRequest(Object source, EventArgs e)
  22:          {
  23:              HttpContext context = ((HttpApplication)source).Context;
  24:   
  25:              // Do something with context near the beginning of request processing.
  26:   
  27:              if (TerminateRequest())
  28:              {
  29:                  context.Response.End();
  30:                  return;
  31:              }
  32:          }
  33:          #endregion
  34:   
  35:          private void Application_EndRequest(Object source, EventArgs e)
  36:          {
  37:              HttpContext context = ((HttpApplication)source).Context;
  38:   
  39:              // Do something with context near the end of request processing.
  40:          }
  41:   
  42:          private bool TerminateRequest()
  43:          {
  44:              return false;
  45:          }
  46:      }
  47:  }

A middleware handles this by not calling Invoke on the next middleware in the pipeline. Keep in mind that this does not fully terminate the request, because previous middlewares will still be invoked when the response makes its way back through the pipeline.

[!code-csharpMain]

   1:  using Microsoft.AspNetCore.Builder;
   2:  using Microsoft.AspNetCore.Http;
   3:  using System.Threading.Tasks;
   4:   
   5:  namespace MyApp.Middleware
   6:  {
   7:      public class MyTerminatingMiddleware
   8:      {
   9:          private readonly RequestDelegate _next;
  10:   
  11:          public MyTerminatingMiddleware(RequestDelegate next)
  12:          {
  13:              _next = next;
  14:          }
  15:   
  16:          #region snippet_Terminate
  17:          // ASP.NET Core middleware that may terminate the request
  18:   
  19:          public async Task Invoke(HttpContext context)
  20:          {
  21:              // Do something with context near the beginning of request processing.
  22:   
  23:              if (!TerminateRequest())
  24:                  await _next.Invoke(context);
  25:   
  26:              // Clean up.
  27:          }
  28:          #endregion
  29:   
  30:          private bool TerminateRequest()
  31:          {
  32:              return false;
  33:          }
  34:      }
  35:   
  36:      public static class MyTerminatingMiddlewareExtensions
  37:      {
  38:          public static IApplicationBuilder UseMyTerminatingMiddleware(this IApplicationBuilder builder)
  39:          {
  40:              return builder.UseMiddleware<MyTerminatingMiddleware>();
  41:          }
  42:      }
  43:  }

When you migrate your module’s functionality to your new middleware, you may find that your code doesn’t compile because the HttpContext class has significantly changed in ASP.NET Core. Later on, you’ll see how to migrate to the new ASP.NET Core HttpContext.

Migrating module insertion into the request pipeline

HTTP modules are typically added to the request pipeline using Web.config:

[!code-xmlMain]

   1:  <?xml version="1.0" encoding="utf-8"?>
   2:  <!--ASP.NET 4 web.config-->
   3:  <configuration>
   4:    <configSections>
   5:      
   6:      <section name="entityFramework"
   7:        type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
   8:        requirePermission="false"/>
   9:    </configSections>
  10:    <connectionStrings>
  11:      <add name="DefaultConnection"
  12:        connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-Asp.Net4-20160127091227.mdf;Initial Catalog=aspnet-Asp.Net4-20160127091227;Integrated Security=True"
  13:        providerName="System.Data.SqlClient"/>
  14:    </connectionStrings>
  15:    <appSettings>
  16:      <add key="owin:AutomaticAppStartup" value="false"/>
  17:      <add key="webpages:Version" value="3.0.0.0"/>
  18:      <add key="webpages:Enabled" value="false"/>
  19:      <add key="ClientValidationEnabled" value="true"/>
  20:      <add key="UnobtrusiveJavaScriptEnabled" value="true"/>
  21:    </appSettings>
  22:    <system.web>
  23:      <authentication mode="None"/>
  24:      <compilation debug="true" targetFramework="4.6"/>
  25:      <httpRuntime targetFramework="4.6"/>
  26:   
  27:      <httpHandlers>
  28:        <add path="*.report" verb="*" type="Asp.Net4.HttpHandlers.ReportHandler"/>
  29:      </httpHandlers>
  30:      
  31:    </system.web>
  32:    <system.webServer>
  33:      <modules>
  34:        <remove name="FormsAuthentication"/>
  35:   
  36:        <add name="MyModule" type="MyApp.Modules.MyModule"/>
  37:        
  38:        <add name="MyTerminatingModule" type="MyApp.Modules.MyTerminatingModule"/>
  39:        
  40:        
  41:        
  42:   
  43:      </modules>
  44:   
  45:      <validation validateIntegratedModeConfiguration="false"/>
  46:      <handlers>
  47:        <add name="MyHandler" verb="*" path="*.report" type="MyApp.HttpHandlers.MyHandler" resourceType="Unspecified" preCondition="integratedMode"/>
  48:      </handlers>
  49:      
  50:    </system.webServer>
  51:    <runtime>
  52:      <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
  53:        <dependentAssembly>
  54:          <assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35"/>
  55:          <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0"/>
  56:        </dependentAssembly>
  57:        <dependentAssembly>
  58:          <assemblyIdentity name="Microsoft.Owin.Security.OAuth" publicKeyToken="31bf3856ad364e35"/>
  59:          <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0"/>
  60:        </dependentAssembly>
  61:        <dependentAssembly>
  62:          <assemblyIdentity name="Microsoft.Owin.Security.Cookies" publicKeyToken="31bf3856ad364e35"/>
  63:          <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0"/>
  64:        </dependentAssembly>
  65:        <dependentAssembly>
  66:          <assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35"/>
  67:          <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0"/>
  68:        </dependentAssembly>
  69:        <dependentAssembly>
  70:          <assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed"/>
  71:          <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0"/>
  72:        </dependentAssembly>
  73:        <dependentAssembly>
  74:          <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35"/>
  75:          <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0"/>
  76:        </dependentAssembly>
  77:        <dependentAssembly>
  78:          <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35"/>
  79:          <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234"/>
  80:        </dependentAssembly>
  81:        <dependentAssembly>
  82:          <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35"/>
  83:          <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
  84:        </dependentAssembly>
  85:        <dependentAssembly>
  86:          <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35"/>
  87:          <bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0"/>
  88:        </dependentAssembly>
  89:        <dependentAssembly>
  90:          <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35"/>
  91:          <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
  92:        </dependentAssembly>
  93:      </assemblyBinding>
  94:    </runtime>
  95:    <entityFramework>
  96:      <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework"/>
  97:      <providers>
  98:        <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer"/>
  99:      </providers>
 100:    </entityFramework>
 101:  </configuration>

Convert this by adding your new middleware to the request pipeline in your Startup class:

[!code-csharpMain]

   1:  // ASP.NET Core Startup class
   2:   
   3:  using System;
   4:  using System.Collections.Generic;
   5:  using System.Linq;
   6:  using System.Threading.Tasks;
   7:  using Microsoft.AspNetCore.Builder;
   8:  using Microsoft.AspNetCore.Hosting;
   9:  using Microsoft.Extensions.Configuration;
  10:  using Microsoft.Extensions.DependencyInjection;
  11:  using Microsoft.Extensions.Logging;
  12:  using MyApp.Middleware;
  13:   
  14:  namespace Asp.Net.Core
  15:  {
  16:      public class Startup
  17:      {
  18:          #region snippet_Ctor
  19:          public Startup(IHostingEnvironment env)
  20:          {
  21:              var builder = new ConfigurationBuilder()
  22:                  .SetBasePath(env.ContentRootPath)
  23:                  .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
  24:                  .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
  25:                  .AddEnvironmentVariables();
  26:              Configuration = builder.Build();
  27:          }
  28:          #endregion
  29:   
  30:          public IConfigurationRoot Configuration { get; }
  31:   
  32:          // This method gets called by the runtime. Use this method to add services to the container.
  33:          #region snippet_ConfigureServices
  34:          public void ConfigureServices(IServiceCollection services)
  35:          {
  36:              // Setup options service
  37:              services.AddOptions();
  38:   
  39:              // Load options from section "MyMiddlewareOptionsSection"
  40:              services.Configure<MyMiddlewareOptions>(
  41:                  Configuration.GetSection("MyMiddlewareOptionsSection"));
  42:   
  43:              // Add framework services.
  44:              services.AddMvc();
  45:          }
  46:          #endregion
  47:   
  48:          // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  49:          #region snippet_Configure
  50:          public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
  51:          {
  52:              loggerFactory.AddConsole(Configuration.GetSection("Logging"));
  53:              loggerFactory.AddDebug();
  54:   
  55:              if (env.IsDevelopment())
  56:              {
  57:                  app.UseDeveloperExceptionPage();
  58:                  app.UseBrowserLink();
  59:              }
  60:              else
  61:              {
  62:                  app.UseExceptionHandler("/Home/Error");
  63:              }
  64:   
  65:              app.UseMyMiddleware();
  66:   
  67:              app.UseMyMiddlewareWithParams();
  68:   
  69:              var myMiddlewareOptions = Configuration.GetSection("MyMiddlewareOptionsSection").Get<MyMiddlewareOptions>();
  70:              var myMiddlewareOptions2 = Configuration.GetSection("MyMiddlewareOptionsSection2").Get<MyMiddlewareOptions>();
  71:              app.UseMyMiddlewareWithParams(myMiddlewareOptions);
  72:              app.UseMyMiddlewareWithParams(myMiddlewareOptions2);
  73:   
  74:              app.UseMyTerminatingMiddleware();
  75:   
  76:              // Create branch to the MyHandlerMiddleware. 
  77:              // All requests ending in .report will follow this branch.
  78:              app.MapWhen(
  79:                  context => context.Request.Path.ToString().EndsWith(".report"),
  80:                  appBranch => {
  81:                      // ... optionally add more middleware to this branch
  82:                      appBranch.UseMyHandler();
  83:                  });
  84:   
  85:              app.MapWhen(
  86:                  context => context.Request.Path.ToString().EndsWith(".context"),
  87:                  appBranch => {
  88:                      appBranch.UseHttpContextDemoMiddleware();
  89:                  });
  90:   
  91:              app.UseStaticFiles();
  92:   
  93:              app.UseMvc(routes =>
  94:              {
  95:                  routes.MapRoute(
  96:                      name: "default",
  97:                      template: "{controller=Home}/{action=Index}/{id?}");
  98:              });
  99:          }
 100:          #endregion
 101:      }
 102:  }
 103:   
 104:   
 105:   
 106:   
 107:   
 108:   
 109:   
 110:   
 111:   
 112:   
 113:   
 114:   
 115:   
 116:   
 117:   
 118:   
 119:   
 120:   
 121:   
 122:   
 123:  //

The exact spot in the pipeline where you insert your new middleware depends on the event that it handled as a module (BeginRequest, EndRequest, etc.) and its order in your list of modules in Web.config.

As previously stated, there is no application life cycle in ASP.NET Core and the order in which responses are processed by middleware differs from the order used by modules. This could make your ordering decision more challenging.

If ordering becomes a problem, you could split your module into multiple middleware components that can be ordered independently.

Migrating handler code to middleware

An HTTP handler looks something like this:

[!code-csharpMain]

   1:  // ASP.NET 4 handler
   2:   
   3:  using System.Web;
   4:   
   5:  namespace MyApp.HttpHandlers
   6:  {
   7:      public class MyHandler : IHttpHandler
   8:      {
   9:          public bool IsReusable { get { return true; } }
  10:   
  11:          public void ProcessRequest(HttpContext context)
  12:          {
  13:              string response = GenerateResponse(context);
  14:   
  15:              context.Response.ContentType = GetContentType();
  16:              context.Response.Output.Write(response);
  17:          }
  18:   
  19:          // ...
  20:   
  21:          private string GenerateResponse(HttpContext context)
  22:          {
  23:              string title = context.Request.QueryString["title"];
  24:              return string.Format("Title of the report: {0}", title);
  25:          }
  26:   
  27:          private string GetContentType()
  28:          {
  29:              return "text/plain";
  30:          }
  31:      }
  32:  }

In your ASP.NET Core project, you would translate this to a middleware similar to this:

[!code-csharpMain]

   1:  // ASP.NET Core middleware migrated from a handler
   2:   
   3:  using Microsoft.AspNetCore.Builder;
   4:  using Microsoft.AspNetCore.Http;
   5:  using System.Threading.Tasks;
   6:   
   7:  namespace MyApp.Middleware
   8:  {
   9:      public class MyHandlerMiddleware
  10:      {
  11:   
  12:          // Must have constructor with this signature, otherwise exception at run time
  13:          public MyHandlerMiddleware(RequestDelegate next)
  14:          {
  15:              // This is an HTTP Handler, so no need to store next
  16:          }
  17:   
  18:          public async Task Invoke(HttpContext context)
  19:          {
  20:              string response = GenerateResponse(context);
  21:   
  22:              context.Response.ContentType = GetContentType();
  23:              await context.Response.WriteAsync(response);
  24:          }
  25:   
  26:          // ...
  27:   
  28:          private string GenerateResponse(HttpContext context)
  29:          {
  30:              string title = context.Request.Query["title"];
  31:              return string.Format("Title of the report: {0}", title);
  32:          }
  33:   
  34:          private string GetContentType()
  35:          {
  36:              return "text/plain";
  37:          }
  38:      }
  39:   
  40:      public static class MyHandlerExtensions
  41:      {
  42:          public static IApplicationBuilder UseMyHandler(this IApplicationBuilder builder)
  43:          {
  44:              return builder.UseMiddleware<MyHandlerMiddleware>();
  45:          }
  46:      }
  47:  }
  48:   

This middleware is very similar to the middleware corresponding to modules. The only real difference is that here there is no call to _next.Invoke(context). That makes sense, because the handler is at the end of the request pipeline, so there will be no next middleware to invoke.

Migrating handler insertion into the request pipeline

Configuring an HTTP handler is done in Web.config and looks something like this:

[!code-xmlMain]

   1:  <?xml version="1.0" encoding="utf-8"?>
   2:  <!--ASP.NET 4 web.config-->
   3:  <configuration>
   4:    <configSections>
   5:      
   6:      <section name="entityFramework"
   7:        type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
   8:        requirePermission="false"/>
   9:    </configSections>
  10:    <connectionStrings>
  11:      <add name="DefaultConnection"
  12:        connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-Asp.Net4-20160127091227.mdf;Initial Catalog=aspnet-Asp.Net4-20160127091227;Integrated Security=True"
  13:        providerName="System.Data.SqlClient"/>
  14:    </connectionStrings>
  15:    <appSettings>
  16:      <add key="owin:AutomaticAppStartup" value="false"/>
  17:      <add key="webpages:Version" value="3.0.0.0"/>
  18:      <add key="webpages:Enabled" value="false"/>
  19:      <add key="ClientValidationEnabled" value="true"/>
  20:      <add key="UnobtrusiveJavaScriptEnabled" value="true"/>
  21:    </appSettings>
  22:    <system.web>
  23:      <authentication mode="None"/>
  24:      <compilation debug="true" targetFramework="4.6"/>
  25:      <httpRuntime targetFramework="4.6"/>
  26:   
  27:      <httpHandlers>
  28:        <add path="*.report" verb="*" type="Asp.Net4.HttpHandlers.ReportHandler"/>
  29:      </httpHandlers>
  30:      
  31:    </system.web>
  32:    <system.webServer>
  33:      <modules>
  34:        <remove name="FormsAuthentication"/>
  35:   
  36:        <add name="MyModule" type="MyApp.Modules.MyModule"/>
  37:        
  38:        <add name="MyTerminatingModule" type="MyApp.Modules.MyTerminatingModule"/>
  39:        
  40:        
  41:        
  42:   
  43:      </modules>
  44:   
  45:      <validation validateIntegratedModeConfiguration="false"/>
  46:      <handlers>
  47:        <add name="MyHandler" verb="*" path="*.report" type="MyApp.HttpHandlers.MyHandler" resourceType="Unspecified" preCondition="integratedMode"/>
  48:      </handlers>
  49:      
  50:    </system.webServer>
  51:    <runtime>
  52:      <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
  53:        <dependentAssembly>
  54:          <assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35"/>
  55:          <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0"/>
  56:        </dependentAssembly>
  57:        <dependentAssembly>
  58:          <assemblyIdentity name="Microsoft.Owin.Security.OAuth" publicKeyToken="31bf3856ad364e35"/>
  59:          <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0"/>
  60:        </dependentAssembly>
  61:        <dependentAssembly>
  62:          <assemblyIdentity name="Microsoft.Owin.Security.Cookies" publicKeyToken="31bf3856ad364e35"/>
  63:          <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0"/>
  64:        </dependentAssembly>
  65:        <dependentAssembly>
  66:          <assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35"/>
  67:          <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0"/>
  68:        </dependentAssembly>
  69:        <dependentAssembly>
  70:          <assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed"/>
  71:          <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0"/>
  72:        </dependentAssembly>
  73:        <dependentAssembly>
  74:          <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35"/>
  75:          <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0"/>
  76:        </dependentAssembly>
  77:        <dependentAssembly>
  78:          <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35"/>
  79:          <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234"/>
  80:        </dependentAssembly>
  81:        <dependentAssembly>
  82:          <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35"/>
  83:          <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
  84:        </dependentAssembly>
  85:        <dependentAssembly>
  86:          <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35"/>
  87:          <bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0"/>
  88:        </dependentAssembly>
  89:        <dependentAssembly>
  90:          <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35"/>
  91:          <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
  92:        </dependentAssembly>
  93:      </assemblyBinding>
  94:    </runtime>
  95:    <entityFramework>
  96:      <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework"/>
  97:      <providers>
  98:        <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer"/>
  99:      </providers>
 100:    </entityFramework>
 101:  </configuration>

You could convert this by adding your new handler middleware to the request pipeline in your Startup class, similar to middleware converted from modules. The problem with that approach is that it would send all requests to your new handler middleware. However, you only want requests with a given extension to reach your middleware. That would give you the same functionality you had with your HTTP handler.

One solution is to branch the pipeline for requests with a given extension, using the MapWhen extension method. You do this in the same Configure method where you add the other middleware:

[!code-csharpMain]

   1:  // ASP.NET Core Startup class
   2:   
   3:  using System;
   4:  using System.Collections.Generic;
   5:  using System.Linq;
   6:  using System.Threading.Tasks;
   7:  using Microsoft.AspNetCore.Builder;
   8:  using Microsoft.AspNetCore.Hosting;
   9:  using Microsoft.Extensions.Configuration;
  10:  using Microsoft.Extensions.DependencyInjection;
  11:  using Microsoft.Extensions.Logging;
  12:  using MyApp.Middleware;
  13:   
  14:  namespace Asp.Net.Core
  15:  {
  16:      public class Startup
  17:      {
  18:          #region snippet_Ctor
  19:          public Startup(IHostingEnvironment env)
  20:          {
  21:              var builder = new ConfigurationBuilder()
  22:                  .SetBasePath(env.ContentRootPath)
  23:                  .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
  24:                  .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
  25:                  .AddEnvironmentVariables();
  26:              Configuration = builder.Build();
  27:          }
  28:          #endregion
  29:   
  30:          public IConfigurationRoot Configuration { get; }
  31:   
  32:          // This method gets called by the runtime. Use this method to add services to the container.
  33:          #region snippet_ConfigureServices
  34:          public void ConfigureServices(IServiceCollection services)
  35:          {
  36:              // Setup options service
  37:              services.AddOptions();
  38:   
  39:              // Load options from section "MyMiddlewareOptionsSection"
  40:              services.Configure<MyMiddlewareOptions>(
  41:                  Configuration.GetSection("MyMiddlewareOptionsSection"));
  42:   
  43:              // Add framework services.
  44:              services.AddMvc();
  45:          }
  46:          #endregion
  47:   
  48:          // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  49:          #region snippet_Configure
  50:          public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
  51:          {
  52:              loggerFactory.AddConsole(Configuration.GetSection("Logging"));
  53:              loggerFactory.AddDebug();
  54:   
  55:              if (env.IsDevelopment())
  56:              {
  57:                  app.UseDeveloperExceptionPage();
  58:                  app.UseBrowserLink();
  59:              }
  60:              else
  61:              {
  62:                  app.UseExceptionHandler("/Home/Error");
  63:              }
  64:   
  65:              app.UseMyMiddleware();
  66:   
  67:              app.UseMyMiddlewareWithParams();
  68:   
  69:              var myMiddlewareOptions = Configuration.GetSection("MyMiddlewareOptionsSection").Get<MyMiddlewareOptions>();
  70:              var myMiddlewareOptions2 = Configuration.GetSection("MyMiddlewareOptionsSection2").Get<MyMiddlewareOptions>();
  71:              app.UseMyMiddlewareWithParams(myMiddlewareOptions);
  72:              app.UseMyMiddlewareWithParams(myMiddlewareOptions2);
  73:   
  74:              app.UseMyTerminatingMiddleware();
  75:   
  76:              // Create branch to the MyHandlerMiddleware. 
  77:              // All requests ending in .report will follow this branch.
  78:              app.MapWhen(
  79:                  context => context.Request.Path.ToString().EndsWith(".report"),
  80:                  appBranch => {
  81:                      // ... optionally add more middleware to this branch
  82:                      appBranch.UseMyHandler();
  83:                  });
  84:   
  85:              app.MapWhen(
  86:                  context => context.Request.Path.ToString().EndsWith(".context"),
  87:                  appBranch => {
  88:                      appBranch.UseHttpContextDemoMiddleware();
  89:                  });
  90:   
  91:              app.UseStaticFiles();
  92:   
  93:              app.UseMvc(routes =>
  94:              {
  95:                  routes.MapRoute(
  96:                      name: "default",
  97:                      template: "{controller=Home}/{action=Index}/{id?}");
  98:              });
  99:          }
 100:          #endregion
 101:      }
 102:  }
 103:   
 104:   
 105:   
 106:   
 107:   
 108:   
 109:   
 110:   
 111:   
 112:   
 113:   
 114:   
 115:   
 116:   
 117:   
 118:   
 119:   
 120:   
 121:   
 122:   
 123:  //

MapWhen takes these parameters:

  1. A lambda that takes the HttpContext and returns true if the request should go down the branch. This means you can branch requests not just based on their extension, but also on request headers, query string parameters, etc.

  2. A lambda that takes an IApplicationBuilder and adds all the middleware for the branch. This means you can add additional middleware to the branch in front of your handler middleware.

Middleware added to the pipeline before the branch will be invoked on all requests; the branch will have no impact on them.

Loading middleware options using the options pattern

Some modules and handlers have configuration options that are stored in Web.config. However, in ASP.NET Core a new configuration model is used in place of Web.config.

The new (xref:)configuration system gives you these options to solve this:

  1. Create a class to hold your middleware options, for example:

    [!code-csharpMain]

       1:  using Microsoft.AspNetCore.Builder;
       2:  using Microsoft.AspNetCore.Http;
       3:  using Microsoft.Extensions.Options;
       4:  using System.Threading.Tasks;
       5:   
       6:  namespace MyApp.Middleware
       7:  {
       8:      #region snippet_Options
       9:      public class MyMiddlewareOptions
      10:      {
      11:          public string Param1 { get; set; }
      12:          public string Param2 { get; set; }
      13:      }
      14:      #endregion
      15:   
      16:      #region snippet_MiddlewareWithParams
      17:      public class MyMiddlewareWithParams
      18:      {
      19:          private readonly RequestDelegate _next;
      20:          private readonly MyMiddlewareOptions _myMiddlewareOptions;
      21:   
      22:          public MyMiddlewareWithParams(RequestDelegate next,
      23:              IOptions<MyMiddlewareOptions> optionsAccessor)
      24:          {
      25:              _next = next;
      26:              _myMiddlewareOptions = optionsAccessor.Value;
      27:          }
      28:   
      29:          public async Task Invoke(HttpContext context)
      30:          {
      31:              // Do something with context near the beginning of request processing
      32:              // using configuration in _myMiddlewareOptions
      33:   
      34:              await _next.Invoke(context);
      35:   
      36:              // Do something with context near the end of request processing
      37:              // using configuration in _myMiddlewareOptions
      38:          }
      39:      }
      40:      #endregion
      41:   
      42:      #region snippet_Extensions
      43:      public static class MyMiddlewareWithParamsExtensions
      44:      {
      45:          public static IApplicationBuilder UseMyMiddlewareWithParams(
      46:              this IApplicationBuilder builder)
      47:          {
      48:              return builder.UseMiddleware<MyMiddlewareWithParams>();
      49:          }
      50:   
      51:          public static IApplicationBuilder UseMyMiddlewareWithParams(
      52:              this IApplicationBuilder builder, MyMiddlewareOptions myMiddlewareOptions)
      53:          {
      54:              return builder.UseMiddleware<MyMiddlewareWithParams>(
      55:                  new OptionsWrapper<MyMiddlewareOptions>(myMiddlewareOptions));
      56:          }
      57:      }
      58:      #endregion
      59:  }

  2. Store the option values

    The configuration system allows you to store option values anywhere you want. However, most sites use appsettings.json, so we’ll take that approach:

    [!code-jsonMain]

       1:  {
       2:    "Logging": {
       3:      "IncludeScopes": false,
       4:      "LogLevel": {
       5:        "Default": "Debug",
       6:        "System": "Information",
       7:        "Microsoft": "Information"
       8:      }
       9:    },
      10:    "MyMiddlewareOptionsSection2": {
      11:      "Param1": "Param1Value2",
      12:      "Param2": "Param2Value2"
      13:    },
      14:    "MyMiddlewareOptionsSection": {
      15:      "Param1": "Param1Value",
      16:      "Param2": "Param2Value"
      17:    }
      18:  }

    MyMiddlewareOptionsSection here is a section name. It doesn’t have to be the same as the name of your options class.

  3. Associate the option values with the options class

    The options pattern uses ASP.NET Core’s dependency injection framework to associate the options type (such as MyMiddlewareOptions) with a MyMiddlewareOptions object that has the actual options.

    Update your Startup class:

    1. If you’re using appsettings.json, add it to the configuration builder in the Startup constructor:

    [!code-csharpMain]

       1:  // ASP.NET Core Startup class
       2:   
       3:  using System;
       4:  using System.Collections.Generic;
       5:  using System.Linq;
       6:  using System.Threading.Tasks;
       7:  using Microsoft.AspNetCore.Builder;
       8:  using Microsoft.AspNetCore.Hosting;
       9:  using Microsoft.Extensions.Configuration;
      10:  using Microsoft.Extensions.DependencyInjection;
      11:  using Microsoft.Extensions.Logging;
      12:  using MyApp.Middleware;
      13:   
      14:  namespace Asp.Net.Core
      15:  {
      16:      public class Startup
      17:      {
      18:          #region snippet_Ctor
      19:          public Startup(IHostingEnvironment env)
      20:          {
      21:              var builder = new ConfigurationBuilder()
      22:                  .SetBasePath(env.ContentRootPath)
      23:                  .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
      24:                  .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
      25:                  .AddEnvironmentVariables();
      26:              Configuration = builder.Build();
      27:          }
      28:          #endregion
      29:   
      30:          public IConfigurationRoot Configuration { get; }
      31:   
      32:          // This method gets called by the runtime. Use this method to add services to the container.
      33:          #region snippet_ConfigureServices
      34:          public void ConfigureServices(IServiceCollection services)
      35:          {
      36:              // Setup options service
      37:              services.AddOptions();
      38:   
      39:              // Load options from section "MyMiddlewareOptionsSection"
      40:              services.Configure<MyMiddlewareOptions>(
      41:                  Configuration.GetSection("MyMiddlewareOptionsSection"));
      42:   
      43:              // Add framework services.
      44:              services.AddMvc();
      45:          }
      46:          #endregion
      47:   
      48:          // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
      49:          #region snippet_Configure
      50:          public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
      51:          {
      52:              loggerFactory.AddConsole(Configuration.GetSection("Logging"));
      53:              loggerFactory.AddDebug();
      54:   
      55:              if (env.IsDevelopment())
      56:              {
      57:                  app.UseDeveloperExceptionPage();
      58:                  app.UseBrowserLink();
      59:              }
      60:              else
      61:              {
      62:                  app.UseExceptionHandler("/Home/Error");
      63:              }
      64:   
      65:              app.UseMyMiddleware();
      66:   
      67:              app.UseMyMiddlewareWithParams();
      68:   
      69:              var myMiddlewareOptions = Configuration.GetSection("MyMiddlewareOptionsSection").Get<MyMiddlewareOptions>();
      70:              var myMiddlewareOptions2 = Configuration.GetSection("MyMiddlewareOptionsSection2").Get<MyMiddlewareOptions>();
      71:              app.UseMyMiddlewareWithParams(myMiddlewareOptions);
      72:              app.UseMyMiddlewareWithParams(myMiddlewareOptions2);
      73:   
      74:              app.UseMyTerminatingMiddleware();
      75:   
      76:              // Create branch to the MyHandlerMiddleware. 
      77:              // All requests ending in .report will follow this branch.
      78:              app.MapWhen(
      79:                  context => context.Request.Path.ToString().EndsWith(".report"),
      80:                  appBranch => {
      81:                      // ... optionally add more middleware to this branch
      82:                      appBranch.UseMyHandler();
      83:                  });
      84:   
      85:              app.MapWhen(
      86:                  context => context.Request.Path.ToString().EndsWith(".context"),
      87:                  appBranch => {
      88:                      appBranch.UseHttpContextDemoMiddleware();
      89:                  });
      90:   
      91:              app.UseStaticFiles();
      92:   
      93:              app.UseMvc(routes =>
      94:              {
      95:                  routes.MapRoute(
      96:                      name: "default",
      97:                      template: "{controller=Home}/{action=Index}/{id?}");
      98:              });
      99:          }
     100:          #endregion
     101:      }
     102:  }
     103:   
     104:   
     105:   
     106:   
     107:   
     108:   
     109:   
     110:   
     111:   
     112:   
     113:   
     114:   
     115:   
     116:   
     117:   
     118:   
     119:   
     120:   
     121:   
     122:   
     123:  //

    1. Configure the options service:

    [!code-csharpMain]

       1:  // ASP.NET Core Startup class
       2:   
       3:  using System;
       4:  using System.Collections.Generic;
       5:  using System.Linq;
       6:  using System.Threading.Tasks;
       7:  using Microsoft.AspNetCore.Builder;
       8:  using Microsoft.AspNetCore.Hosting;
       9:  using Microsoft.Extensions.Configuration;
      10:  using Microsoft.Extensions.DependencyInjection;
      11:  using Microsoft.Extensions.Logging;
      12:  using MyApp.Middleware;
      13:   
      14:  namespace Asp.Net.Core
      15:  {
      16:      public class Startup
      17:      {
      18:          #region snippet_Ctor
      19:          public Startup(IHostingEnvironment env)
      20:          {
      21:              var builder = new ConfigurationBuilder()
      22:                  .SetBasePath(env.ContentRootPath)
      23:                  .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
      24:                  .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
      25:                  .AddEnvironmentVariables();
      26:              Configuration = builder.Build();
      27:          }
      28:          #endregion
      29:   
      30:          public IConfigurationRoot Configuration { get; }
      31:   
      32:          // This method gets called by the runtime. Use this method to add services to the container.
      33:          #region snippet_ConfigureServices
      34:          public void ConfigureServices(IServiceCollection services)
      35:          {
      36:              // Setup options service
      37:              services.AddOptions();
      38:   
      39:              // Load options from section "MyMiddlewareOptionsSection"
      40:              services.Configure<MyMiddlewareOptions>(
      41:                  Configuration.GetSection("MyMiddlewareOptionsSection"));
      42:   
      43:              // Add framework services.
      44:              services.AddMvc();
      45:          }
      46:          #endregion
      47:   
      48:          // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
      49:          #region snippet_Configure
      50:          public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
      51:          {
      52:              loggerFactory.AddConsole(Configuration.GetSection("Logging"));
      53:              loggerFactory.AddDebug();
      54:   
      55:              if (env.IsDevelopment())
      56:              {
      57:                  app.UseDeveloperExceptionPage();
      58:                  app.UseBrowserLink();
      59:              }
      60:              else
      61:              {
      62:                  app.UseExceptionHandler("/Home/Error");
      63:              }
      64:   
      65:              app.UseMyMiddleware();
      66:   
      67:              app.UseMyMiddlewareWithParams();
      68:   
      69:              var myMiddlewareOptions = Configuration.GetSection("MyMiddlewareOptionsSection").Get<MyMiddlewareOptions>();
      70:              var myMiddlewareOptions2 = Configuration.GetSection("MyMiddlewareOptionsSection2").Get<MyMiddlewareOptions>();
      71:              app.UseMyMiddlewareWithParams(myMiddlewareOptions);
      72:              app.UseMyMiddlewareWithParams(myMiddlewareOptions2);
      73:   
      74:              app.UseMyTerminatingMiddleware();
      75:   
      76:              // Create branch to the MyHandlerMiddleware. 
      77:              // All requests ending in .report will follow this branch.
      78:              app.MapWhen(
      79:                  context => context.Request.Path.ToString().EndsWith(".report"),
      80:                  appBranch => {
      81:                      // ... optionally add more middleware to this branch
      82:                      appBranch.UseMyHandler();
      83:                  });
      84:   
      85:              app.MapWhen(
      86:                  context => context.Request.Path.ToString().EndsWith(".context"),
      87:                  appBranch => {
      88:                      appBranch.UseHttpContextDemoMiddleware();
      89:                  });
      90:   
      91:              app.UseStaticFiles();
      92:   
      93:              app.UseMvc(routes =>
      94:              {
      95:                  routes.MapRoute(
      96:                      name: "default",
      97:                      template: "{controller=Home}/{action=Index}/{id?}");
      98:              });
      99:          }
     100:          #endregion
     101:      }
     102:  }
     103:   
     104:   
     105:   
     106:   
     107:   
     108:   
     109:   
     110:   
     111:   
     112:   
     113:   
     114:   
     115:   
     116:   
     117:   
     118:   
     119:   
     120:   
     121:   
     122:   
     123:  //

    1. Associate your options with your options class:

    [!code-csharpMain]

       1:  // ASP.NET Core Startup class
       2:   
       3:  using System;
       4:  using System.Collections.Generic;
       5:  using System.Linq;
       6:  using System.Threading.Tasks;
       7:  using Microsoft.AspNetCore.Builder;
       8:  using Microsoft.AspNetCore.Hosting;
       9:  using Microsoft.Extensions.Configuration;
      10:  using Microsoft.Extensions.DependencyInjection;
      11:  using Microsoft.Extensions.Logging;
      12:  using MyApp.Middleware;
      13:   
      14:  namespace Asp.Net.Core
      15:  {
      16:      public class Startup
      17:      {
      18:          #region snippet_Ctor
      19:          public Startup(IHostingEnvironment env)
      20:          {
      21:              var builder = new ConfigurationBuilder()
      22:                  .SetBasePath(env.ContentRootPath)
      23:                  .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
      24:                  .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
      25:                  .AddEnvironmentVariables();
      26:              Configuration = builder.Build();
      27:          }
      28:          #endregion
      29:   
      30:          public IConfigurationRoot Configuration { get; }
      31:   
      32:          // This method gets called by the runtime. Use this method to add services to the container.
      33:          #region snippet_ConfigureServices
      34:          public void ConfigureServices(IServiceCollection services)
      35:          {
      36:              // Setup options service
      37:              services.AddOptions();
      38:   
      39:              // Load options from section "MyMiddlewareOptionsSection"
      40:              services.Configure<MyMiddlewareOptions>(
      41:                  Configuration.GetSection("MyMiddlewareOptionsSection"));
      42:   
      43:              // Add framework services.
      44:              services.AddMvc();
      45:          }
      46:          #endregion
      47:   
      48:          // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
      49:          #region snippet_Configure
      50:          public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
      51:          {
      52:              loggerFactory.AddConsole(Configuration.GetSection("Logging"));
      53:              loggerFactory.AddDebug();
      54:   
      55:              if (env.IsDevelopment())
      56:              {
      57:                  app.UseDeveloperExceptionPage();
      58:                  app.UseBrowserLink();
      59:              }
      60:              else
      61:              {
      62:                  app.UseExceptionHandler("/Home/Error");
      63:              }
      64:   
      65:              app.UseMyMiddleware();
      66:   
      67:              app.UseMyMiddlewareWithParams();
      68:   
      69:              var myMiddlewareOptions = Configuration.GetSection("MyMiddlewareOptionsSection").Get<MyMiddlewareOptions>();
      70:              var myMiddlewareOptions2 = Configuration.GetSection("MyMiddlewareOptionsSection2").Get<MyMiddlewareOptions>();
      71:              app.UseMyMiddlewareWithParams(myMiddlewareOptions);
      72:              app.UseMyMiddlewareWithParams(myMiddlewareOptions2);
      73:   
      74:              app.UseMyTerminatingMiddleware();
      75:   
      76:              // Create branch to the MyHandlerMiddleware. 
      77:              // All requests ending in .report will follow this branch.
      78:              app.MapWhen(
      79:                  context => context.Request.Path.ToString().EndsWith(".report"),
      80:                  appBranch => {
      81:                      // ... optionally add more middleware to this branch
      82:                      appBranch.UseMyHandler();
      83:                  });
      84:   
      85:              app.MapWhen(
      86:                  context => context.Request.Path.ToString().EndsWith(".context"),
      87:                  appBranch => {
      88:                      appBranch.UseHttpContextDemoMiddleware();
      89:                  });
      90:   
      91:              app.UseStaticFiles();
      92:   
      93:              app.UseMvc(routes =>
      94:              {
      95:                  routes.MapRoute(
      96:                      name: "default",
      97:                      template: "{controller=Home}/{action=Index}/{id?}");
      98:              });
      99:          }
     100:          #endregion
     101:      }
     102:  }
     103:   
     104:   
     105:   
     106:   
     107:   
     108:   
     109:   
     110:   
     111:   
     112:   
     113:   
     114:   
     115:   
     116:   
     117:   
     118:   
     119:   
     120:   
     121:   
     122:   
     123:  //

  4. Inject the options into your middleware constructor. This is similar to injecting options into a controller.

[!code-csharpMain]

   1:  using Microsoft.AspNetCore.Builder;
   2:  using Microsoft.AspNetCore.Http;
   3:  using Microsoft.Extensions.Options;
   4:  using System.Threading.Tasks;
   5:   
   6:  namespace MyApp.Middleware
   7:  {
   8:      #region snippet_Options
   9:      public class MyMiddlewareOptions
  10:      {
  11:          public string Param1 { get; set; }
  12:          public string Param2 { get; set; }
  13:      }
  14:      #endregion
  15:   
  16:      #region snippet_MiddlewareWithParams
  17:      public class MyMiddlewareWithParams
  18:      {
  19:          private readonly RequestDelegate _next;
  20:          private readonly MyMiddlewareOptions _myMiddlewareOptions;
  21:   
  22:          public MyMiddlewareWithParams(RequestDelegate next,
  23:              IOptions<MyMiddlewareOptions> optionsAccessor)
  24:          {
  25:              _next = next;
  26:              _myMiddlewareOptions = optionsAccessor.Value;
  27:          }
  28:   
  29:          public async Task Invoke(HttpContext context)
  30:          {
  31:              // Do something with context near the beginning of request processing
  32:              // using configuration in _myMiddlewareOptions
  33:   
  34:              await _next.Invoke(context);
  35:   
  36:              // Do something with context near the end of request processing
  37:              // using configuration in _myMiddlewareOptions
  38:          }
  39:      }
  40:      #endregion
  41:   
  42:      #region snippet_Extensions
  43:      public static class MyMiddlewareWithParamsExtensions
  44:      {
  45:          public static IApplicationBuilder UseMyMiddlewareWithParams(
  46:              this IApplicationBuilder builder)
  47:          {
  48:              return builder.UseMiddleware<MyMiddlewareWithParams>();
  49:          }
  50:   
  51:          public static IApplicationBuilder UseMyMiddlewareWithParams(
  52:              this IApplicationBuilder builder, MyMiddlewareOptions myMiddlewareOptions)
  53:          {
  54:              return builder.UseMiddleware<MyMiddlewareWithParams>(
  55:                  new OptionsWrapper<MyMiddlewareOptions>(myMiddlewareOptions));
  56:          }
  57:      }
  58:      #endregion
  59:  }

The UseMiddleware extension method that adds your middleware to the IApplicationBuilder takes care of dependency injection.

This is not limited to IOptions objects. Any other object that your middleware requires can be injected this way.

Loading middleware options through direct injection

The options pattern has the advantage that it creates loose coupling between options values and their consumers. Once you’ve associated an options class with the actual options values, any other class can get access to the options through the dependency injection framework. There is no need to pass around options values.

This breaks down though if you want to use the same middleware twice, with different options. For example an authorization middleware used in different branches allowing different roles. You can’t associate two different options objects with the one options class.

The solution is to get the options objects with the actual options values in your Startup class and pass those directly to each instance of your middleware.

  1. Add a second key to appsettings.json

    To add a second set of options to the appsettings.json file, use a new key to uniquely identify it:

    [!code-jsonMain]

       1:  {
       2:    "Logging": {
       3:      "IncludeScopes": false,
       4:      "LogLevel": {
       5:        "Default": "Debug",
       6:        "System": "Information",
       7:        "Microsoft": "Information"
       8:      }
       9:    },
      10:    "MyMiddlewareOptionsSection2": {
      11:      "Param1": "Param1Value2",
      12:      "Param2": "Param2Value2"
      13:    },
      14:    "MyMiddlewareOptionsSection": {
      15:      "Param1": "Param1Value",
      16:      "Param2": "Param2Value"
      17:    }
      18:  }

  2. Retrieve options values and pass them to middleware. The Use... extension method (which adds your middleware to the pipeline) is a logical place to pass in the option values:

    [!code-csharpMain]

       1:  // ASP.NET Core Startup class
       2:   
       3:  using System;
       4:  using System.Collections.Generic;
       5:  using System.Linq;
       6:  using System.Threading.Tasks;
       7:  using Microsoft.AspNetCore.Builder;
       8:  using Microsoft.AspNetCore.Hosting;
       9:  using Microsoft.Extensions.Configuration;
      10:  using Microsoft.Extensions.DependencyInjection;
      11:  using Microsoft.Extensions.Logging;
      12:  using MyApp.Middleware;
      13:   
      14:  namespace Asp.Net.Core
      15:  {
      16:      public class Startup
      17:      {
      18:          #region snippet_Ctor
      19:          public Startup(IHostingEnvironment env)
      20:          {
      21:              var builder = new ConfigurationBuilder()
      22:                  .SetBasePath(env.ContentRootPath)
      23:                  .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
      24:                  .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
      25:                  .AddEnvironmentVariables();
      26:              Configuration = builder.Build();
      27:          }
      28:          #endregion
      29:   
      30:          public IConfigurationRoot Configuration { get; }
      31:   
      32:          // This method gets called by the runtime. Use this method to add services to the container.
      33:          #region snippet_ConfigureServices
      34:          public void ConfigureServices(IServiceCollection services)
      35:          {
      36:              // Setup options service
      37:              services.AddOptions();
      38:   
      39:              // Load options from section "MyMiddlewareOptionsSection"
      40:              services.Configure<MyMiddlewareOptions>(
      41:                  Configuration.GetSection("MyMiddlewareOptionsSection"));
      42:   
      43:              // Add framework services.
      44:              services.AddMvc();
      45:          }
      46:          #endregion
      47:   
      48:          // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
      49:          #region snippet_Configure
      50:          public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
      51:          {
      52:              loggerFactory.AddConsole(Configuration.GetSection("Logging"));
      53:              loggerFactory.AddDebug();
      54:   
      55:              if (env.IsDevelopment())
      56:              {
      57:                  app.UseDeveloperExceptionPage();
      58:                  app.UseBrowserLink();
      59:              }
      60:              else
      61:              {
      62:                  app.UseExceptionHandler("/Home/Error");
      63:              }
      64:   
      65:              app.UseMyMiddleware();
      66:   
      67:              app.UseMyMiddlewareWithParams();
      68:   
      69:              var myMiddlewareOptions = Configuration.GetSection("MyMiddlewareOptionsSection").Get<MyMiddlewareOptions>();
      70:              var myMiddlewareOptions2 = Configuration.GetSection("MyMiddlewareOptionsSection2").Get<MyMiddlewareOptions>();
      71:              app.UseMyMiddlewareWithParams(myMiddlewareOptions);
      72:              app.UseMyMiddlewareWithParams(myMiddlewareOptions2);
      73:   
      74:              app.UseMyTerminatingMiddleware();
      75:   
      76:              // Create branch to the MyHandlerMiddleware. 
      77:              // All requests ending in .report will follow this branch.
      78:              app.MapWhen(
      79:                  context => context.Request.Path.ToString().EndsWith(".report"),
      80:                  appBranch => {
      81:                      // ... optionally add more middleware to this branch
      82:                      appBranch.UseMyHandler();
      83:                  });
      84:   
      85:              app.MapWhen(
      86:                  context => context.Request.Path.ToString().EndsWith(".context"),
      87:                  appBranch => {
      88:                      appBranch.UseHttpContextDemoMiddleware();
      89:                  });
      90:   
      91:              app.UseStaticFiles();
      92:   
      93:              app.UseMvc(routes =>
      94:              {
      95:                  routes.MapRoute(
      96:                      name: "default",
      97:                      template: "{controller=Home}/{action=Index}/{id?}");
      98:              });
      99:          }
     100:          #endregion
     101:      }
     102:  }
     103:   
     104:   
     105:   
     106:   
     107:   
     108:   
     109:   
     110:   
     111:   
     112:   
     113:   
     114:   
     115:   
     116:   
     117:   
     118:   
     119:   
     120:   
     121:   
     122:   
     123:  //

  3. Enable middleware to take an options parameter. Provide an overload of the Use... extension method (that takes the options parameter and passes it to UseMiddleware). When UseMiddleware is called with parameters, it passes the parameters to your middleware constructor when it instantiates the middleware object.

    [!code-csharpMain]

       1:  using Microsoft.AspNetCore.Builder;
       2:  using Microsoft.AspNetCore.Http;
       3:  using Microsoft.Extensions.Options;
       4:  using System.Threading.Tasks;
       5:   
       6:  namespace MyApp.Middleware
       7:  {
       8:      #region snippet_Options
       9:      public class MyMiddlewareOptions
      10:      {
      11:          public string Param1 { get; set; }
      12:          public string Param2 { get; set; }
      13:      }
      14:      #endregion
      15:   
      16:      #region snippet_MiddlewareWithParams
      17:      public class MyMiddlewareWithParams
      18:      {
      19:          private readonly RequestDelegate _next;
      20:          private readonly MyMiddlewareOptions _myMiddlewareOptions;
      21:   
      22:          public MyMiddlewareWithParams(RequestDelegate next,
      23:              IOptions<MyMiddlewareOptions> optionsAccessor)
      24:          {
      25:              _next = next;
      26:              _myMiddlewareOptions = optionsAccessor.Value;
      27:          }
      28:   
      29:          public async Task Invoke(HttpContext context)
      30:          {
      31:              // Do something with context near the beginning of request processing
      32:              // using configuration in _myMiddlewareOptions
      33:   
      34:              await _next.Invoke(context);
      35:   
      36:              // Do something with context near the end of request processing
      37:              // using configuration in _myMiddlewareOptions
      38:          }
      39:      }
      40:      #endregion
      41:   
      42:      #region snippet_Extensions
      43:      public static class MyMiddlewareWithParamsExtensions
      44:      {
      45:          public static IApplicationBuilder UseMyMiddlewareWithParams(
      46:              this IApplicationBuilder builder)
      47:          {
      48:              return builder.UseMiddleware<MyMiddlewareWithParams>();
      49:          }
      50:   
      51:          public static IApplicationBuilder UseMyMiddlewareWithParams(
      52:              this IApplicationBuilder builder, MyMiddlewareOptions myMiddlewareOptions)
      53:          {
      54:              return builder.UseMiddleware<MyMiddlewareWithParams>(
      55:                  new OptionsWrapper<MyMiddlewareOptions>(myMiddlewareOptions));
      56:          }
      57:      }
      58:      #endregion
      59:  }

    Note how this wraps the options object in an OptionsWrapper object. This implements IOptions, as expected by the middleware constructor.

Migrating to the new HttpContext

You saw earlier that the Invoke method in your middleware takes a parameter of type HttpContext:

HttpContext has significantly changed in ASP.NET Core. This section shows how to translate the most commonly used properties of System.Web.HttpContext to the new Microsoft.AspNetCore.Http.HttpContext.

HttpContext

HttpContext.Items translates to:

[!code-csharpMain]

   1:  using Microsoft.AspNetCore.Builder;
   2:  using Microsoft.AspNetCore.Http;
   3:  using System.Collections.Generic;
   4:  using System.Threading.Tasks;
   5:  using Microsoft.Net.Http.Headers;
   6:  using Microsoft.AspNetCore.Http.Extensions;
   7:  using Microsoft.AspNetCore.Routing;
   8:   
   9:  namespace MyApp.Middleware
  10:  {
  11:      public class HttpContextDemoMiddleware
  12:      {
  13:          private readonly RequestDelegate _next;
  14:   
  15:          public HttpContextDemoMiddleware(RequestDelegate next)
  16:          {
  17:              _next = next;
  18:          }
  19:   
  20:          public async Task Invoke(HttpContext httpContext)
  21:          {
  22:              // OnStarting handlers have to be set early during request processing,
  23:              // even though they are used to create the response.
  24:   
  25:              // ----------------------
  26:              // ASP.NET 4 - HttpContext.Response.Headers  
  27:              // ASP.NET 4 - HttpContext.Response.Cookies  
  28:              // 
  29:              // Issue with all response headers is that they will not be sent 
  30:              // after anything has been written to the response body.
  31:              // To solve this, use OnStarting to set a callback that will be called 
  32:              // right before headers are sent. Set the headers in that callback.
  33:              //
  34:              // Setting a cookie results in a Set-Cookie response header.
  35:              // So use an OnStarting handler here as well.
  36:   
  37:              //>40
  38:              httpContext.Response.OnStarting(SetHeaders, state: httpContext);
  39:              httpContext.Response.OnStarting(SetCookies, state: httpContext);
  40:              //<40
  41:   
  42:              // ==================================================================
  43:              // Context
  44:   
  45:              // Unique request ID (no ASP.NET 4 counterpart)
  46:              #region snippet_Trace
  47:              string requestId = httpContext.TraceIdentifier;
  48:              #endregion
  49:   
  50:              // ASP.NET 4 - HttpContext.Items
  51:              #region snippet_Items
  52:              IDictionary<object, object> items = httpContext.Items;
  53:              #endregion
  54:   
  55:              // ==================================================================
  56:              // Request
  57:   
  58:              // ASP.NET 4 - HttpContext.Request.HttpMethod
  59:              #region snippet_Method
  60:              string httpMethod = httpContext.Request.Method;
  61:              #endregion
  62:   
  63:              // ----------
  64:   
  65:              // ASP.NET 4 - HttpContext.Request.QueryString
  66:              #region snippet_Query
  67:              IQueryCollection queryParameters = httpContext.Request.Query;
  68:   
  69:              // If no query parameter "key" used, values will have 0 items
  70:              // If single value used for a key (...?key=v1), values will have 1 item ("v1")
  71:              // If key has multiple values (...?key=v1&key=v2), values will have 2 items ("v1" and "v2")
  72:              IList<string> values = queryParameters["key"];
  73:   
  74:              // If no query parameter "key" used, value will be ""
  75:              // If single value used for a key (...?key=v1), value will be "v1"
  76:              // If key has multiple values (...?key=v1&key=v2), value will be "v1,v2"
  77:              string value = queryParameters["key"].ToString();
  78:              #endregion
  79:   
  80:              // ASP.NET 4 - HttpContext.Request.Url and HttpContext.Request.RawUrl
  81:              #region snippet_Url
  82:              // using Microsoft.AspNetCore.Http.Extensions;
  83:              var url = httpContext.Request.GetDisplayUrl();
  84:              #endregion
  85:   
  86:              // ASP.NET 4 - HttpContext.Request.IsSecureConnection
  87:              #region snippet_Secure
  88:              var isSecureConnection = httpContext.Request.IsHttps;
  89:              #endregion
  90:   
  91:              // ASP.NET 4 - HttpContext.Request.UserHostAddress
  92:              #region snippet_Host
  93:              var userHostAddress = httpContext.Connection.RemoteIpAddress?.ToString();
  94:              #endregion
  95:   
  96:              // ASP.NET 4 - HttpContext.Request.Cookies 
  97:              #region snippet_Cookies
  98:              IRequestCookieCollection cookies = httpContext.Request.Cookies;
  99:              string unknownCookieValue = cookies["unknownCookie"]; // will be null (no exception)
 100:              string knownCookieValue = cookies["cookie1name"];     // will be actual value
 101:              #endregion
 102:   
 103:              // ASP.NET 4 - HttpContext.Request.RequestContext.RouteData
 104:              // using Microsoft.AspNetCore.Routing;
 105:              #region snippet_Route
 106:              var routeValue = httpContext.GetRouteValue("key");
 107:              #endregion
 108:   
 109:              // ASP.NET 4 - HttpContext.Request.Headers
 110:              #region snippet_Headers
 111:              // using Microsoft.AspNetCore.Http.Headers;
 112:              // using Microsoft.Net.Http.Headers;
 113:   
 114:              IHeaderDictionary headersDictionary = httpContext.Request.Headers;
 115:   
 116:              // GetTypedHeaders extension method provides strongly typed access to many headers
 117:              var requestHeaders = httpContext.Request.GetTypedHeaders();
 118:              CacheControlHeaderValue cacheControlHeaderValue = requestHeaders.CacheControl;
 119:   
 120:              // For unknown header, unknownheaderValues has zero items and unknownheaderValue is ""
 121:              IList<string> unknownheaderValues = headersDictionary["unknownheader"];
 122:              string unknownheaderValue = headersDictionary["unknownheader"].ToString();
 123:   
 124:              // For known header, knownheaderValues has 1 item and knownheaderValue is the value
 125:              IList<string> knownheaderValues = headersDictionary[HeaderNames.AcceptLanguage];
 126:              string knownheaderValue = headersDictionary[HeaderNames.AcceptLanguage].ToString();
 127:              #endregion
 128:   
 129:              // ASP.NET 4 - HttpContext.Request.UserAgent
 130:              #region snippet_Agent
 131:              string userAgent = headersDictionary[HeaderNames.UserAgent].ToString();
 132:              #endregion
 133:   
 134:              // ASP.NET 4 - HttpContext.Request.UrlReferrer
 135:              #region snippet_Referrer
 136:              string urlReferrer = headersDictionary[HeaderNames.Referer].ToString();
 137:              #endregion
 138:   
 139:              // ASP.NET 4 - HttpContext.Request.ContentType 
 140:              #region snippet_Type
 141:              // using Microsoft.Net.Http.Headers;
 142:   
 143:              MediaTypeHeaderValue mediaHeaderValue = requestHeaders.ContentType;
 144:              string contentType = mediaHeaderValue?.MediaType;   // ex. application/x-www-form-urlencoded
 145:              string contentMainType = mediaHeaderValue?.Type;    // ex. application
 146:              string contentSubType = mediaHeaderValue?.SubType;  // ex. x-www-form-urlencoded
 147:   
 148:              System.Text.Encoding requestEncoding = mediaHeaderValue?.Encoding;
 149:              #endregion
 150:   
 151:              // ASP.NET 4 - HttpContext.Request.Form 
 152:              #region snippet_Form
 153:              if (httpContext.Request.HasFormContentType)
 154:              {
 155:                  IFormCollection form;
 156:   
 157:                  form = httpContext.Request.Form; // sync
 158:                  // Or
 159:                  form = await httpContext.Request.ReadFormAsync(); // async
 160:   
 161:                  string firstName = form["firstname"];
 162:                  string lastName = form["lastname"];
 163:              }
 164:              #endregion
 165:   
 166:              // ----------
 167:              // See 
 168:              // http://stackoverflow.com/questions/31389781/read-body-twice-in-asp-net-5/
 169:   
 170:              // ASP.NET 4 - HttpContext.Request.InputStream
 171:              // Unlike reading the form, reading the raw body is not from a buffer.
 172:              // So you can only do this once per request.
 173:              // 
 174:              // If you need to read the body multiple times per request, see
 175:              // http://stackoverflow.com/questions/31389781/read-body-twice-in-asp-net-5/
 176:   
 177:              #region snippet_Input
 178:              string inputBody;
 179:              using (var reader = new System.IO.StreamReader(
 180:                  httpContext.Request.Body, System.Text.Encoding.UTF8))
 181:              {
 182:                  inputBody = reader.ReadToEnd();
 183:              }
 184:              #endregion
 185:   
 186:              // Use this middleware as a handler, so no call to 
 187:              // await _next.Invoke(aspnetCoreHttpContext);
 188:   
 189:              // ==================================================================
 190:              // Response
 191:   
 192:              // ASP.NET 4 - HttpContext.Response.Status  
 193:              // ASP.NET 4 - HttpContext.Response.StatusDescription (obsolete, removed from HTTP/2) 
 194:              #region snippet_Status
 195:              // using Microsoft.AspNetCore.Http;
 196:              httpContext.Response.StatusCode = StatusCodes.Status200OK;
 197:              #endregion
 198:   
 199:              // ASP.NET 4 - HttpContext.Response.ContentEncoding and HttpContext.Response.ContentType  
 200:              #region snippet_RespType
 201:              // using Microsoft.Net.Http.Headers;
 202:              var mediaType = new MediaTypeHeaderValue("application/json");
 203:              mediaType.Encoding = System.Text.Encoding.UTF8;
 204:              httpContext.Response.ContentType = mediaType.ToString();
 205:              #endregion
 206:   
 207:              // ASP.NET 4 - HttpContext.Response.ContentType only 
 208:              #region snippet_RespTypeOnly
 209:              httpContext.Response.ContentType = "text/html";
 210:              #endregion
 211:   
 212:              // ASP.NET 4 - HttpContext.Response.Output  
 213:              #region  snippet_Output
 214:              string responseContent = GetResponseContent();
 215:              await httpContext.Response.WriteAsync(responseContent);
 216:              #endregion
 217:          }
 218:   
 219:          #region snippet_SetHeaders
 220:          // using Microsoft.AspNet.Http.Headers;
 221:          // using Microsoft.Net.Http.Headers;
 222:   
 223:          private Task SetHeaders(object context)
 224:          {
 225:              var httpContext = (HttpContext)context;
 226:   
 227:              // Set header with single value
 228:              httpContext.Response.Headers["ResponseHeaderName"] = "headerValue";
 229:   
 230:              // Set header with multiple values
 231:              string[] responseHeaderValues = new string[] { "headerValue1", "headerValue1" };
 232:              httpContext.Response.Headers["ResponseHeaderName"] = responseHeaderValues;
 233:   
 234:              // Translating ASP.NET 4's HttpContext.Response.RedirectLocation  
 235:              httpContext.Response.Headers[HeaderNames.Location] = "http://www.example.com";
 236:              // Or
 237:              httpContext.Response.Redirect("http://www.example.com");
 238:   
 239:              // GetTypedHeaders extension method provides strongly typed access to many headers
 240:              var responseHeaders = httpContext.Response.GetTypedHeaders();
 241:   
 242:              // Translating ASP.NET 4's HttpContext.Response.CacheControl 
 243:              responseHeaders.CacheControl = new CacheControlHeaderValue
 244:              {
 245:                  MaxAge = new System.TimeSpan(365, 0, 0, 0)
 246:                  // Many more properties available 
 247:              };
 248:   
 249:              // If you use .Net 4.6+, Task.CompletedTask will be a bit faster
 250:              return Task.FromResult(0);
 251:          }
 252:          #endregion
 253:   
 254:          #region snippet_SetCookies
 255:          private Task SetCookies(object context)
 256:          {
 257:              var httpContext = (HttpContext)context;
 258:   
 259:              IResponseCookies responseCookies = httpContext.Response.Cookies;
 260:   
 261:              responseCookies.Append("cookie1name", "cookie1value");
 262:              responseCookies.Append("cookie2name", "cookie2value",
 263:                  new CookieOptions { Expires = System.DateTime.Now.AddDays(5), HttpOnly = true });
 264:   
 265:              // If you use .Net 4.6+, Task.CompletedTask will be a bit faster
 266:              return Task.FromResult(0); 
 267:          }
 268:          #endregion
 269:   
 270:          // You would normally use MVC to generate HTML like this.
 271:          private string GetResponseContent()
 272:          {
 273:              return @"
 274:  <!DOCTYPE html>
 275:  <html lang=""en"">
 276:  <head>
 277:      <title>index</title>
 278:  </head>
 279:  <body>
 280:  <form action=""form.context"" method=""post"">
 281:      <input type=""text"" name=""firstname"">
 282:      <input type=""text"" name=""lastname"">
 283:      <input type=""submit"" value=""Submit"">
 284:  </form> 
 285:  </body>
 286:  </html>
 287:  ";
 288:          }
 289:      }
 290:   
 291:      public static class HttpContextDemoMiddlewareExtensions
 292:      {
 293:          public static IApplicationBuilder UseHttpContextDemoMiddleware(this IApplicationBuilder builder)
 294:          {
 295:              return builder.UseMiddleware<HttpContextDemoMiddleware>();
 296:          }
 297:      }
 298:  }

Unique request ID (no System.Web.HttpContext counterpart)

Gives you a unique id for each request. Very useful to include in your logs.

[!code-csharpMain]

   1:  using Microsoft.AspNetCore.Builder;
   2:  using Microsoft.AspNetCore.Http;
   3:  using System.Collections.Generic;
   4:  using System.Threading.Tasks;
   5:  using Microsoft.Net.Http.Headers;
   6:  using Microsoft.AspNetCore.Http.Extensions;
   7:  using Microsoft.AspNetCore.Routing;
   8:   
   9:  namespace MyApp.Middleware
  10:  {
  11:      public class HttpContextDemoMiddleware
  12:      {
  13:          private readonly RequestDelegate _next;
  14:   
  15:          public HttpContextDemoMiddleware(RequestDelegate next)
  16:          {
  17:              _next = next;
  18:          }
  19:   
  20:          public async Task Invoke(HttpContext httpContext)
  21:          {
  22:              // OnStarting handlers have to be set early during request processing,
  23:              // even though they are used to create the response.
  24:   
  25:              // ----------------------
  26:              // ASP.NET 4 - HttpContext.Response.Headers  
  27:              // ASP.NET 4 - HttpContext.Response.Cookies  
  28:              // 
  29:              // Issue with all response headers is that they will not be sent 
  30:              // after anything has been written to the response body.
  31:              // To solve this, use OnStarting to set a callback that will be called 
  32:              // right before headers are sent. Set the headers in that callback.
  33:              //
  34:              // Setting a cookie results in a Set-Cookie response header.
  35:              // So use an OnStarting handler here as well.
  36:   
  37:              //>40
  38:              httpContext.Response.OnStarting(SetHeaders, state: httpContext);
  39:              httpContext.Response.OnStarting(SetCookies, state: httpContext);
  40:              //<40
  41:   
  42:              // ==================================================================
  43:              // Context
  44:   
  45:              // Unique request ID (no ASP.NET 4 counterpart)
  46:              #region snippet_Trace
  47:              string requestId = httpContext.TraceIdentifier;
  48:              #endregion
  49:   
  50:              // ASP.NET 4 - HttpContext.Items
  51:              #region snippet_Items
  52:              IDictionary<object, object> items = httpContext.Items;
  53:              #endregion
  54:   
  55:              // ==================================================================
  56:              // Request
  57:   
  58:              // ASP.NET 4 - HttpContext.Request.HttpMethod
  59:              #region snippet_Method
  60:              string httpMethod = httpContext.Request.Method;
  61:              #endregion
  62:   
  63:              // ----------
  64:   
  65:              // ASP.NET 4 - HttpContext.Request.QueryString
  66:              #region snippet_Query
  67:              IQueryCollection queryParameters = httpContext.Request.Query;
  68:   
  69:              // If no query parameter "key" used, values will have 0 items
  70:              // If single value used for a key (...?key=v1), values will have 1 item ("v1")
  71:              // If key has multiple values (...?key=v1&key=v2), values will have 2 items ("v1" and "v2")
  72:              IList<string> values = queryParameters["key"];
  73:   
  74:              // If no query parameter "key" used, value will be ""
  75:              // If single value used for a key (...?key=v1), value will be "v1"
  76:              // If key has multiple values (...?key=v1&key=v2), value will be "v1,v2"
  77:              string value = queryParameters["key"].ToString();
  78:              #endregion
  79:   
  80:              // ASP.NET 4 - HttpContext.Request.Url and HttpContext.Request.RawUrl
  81:              #region snippet_Url
  82:              // using Microsoft.AspNetCore.Http.Extensions;
  83:              var url = httpContext.Request.GetDisplayUrl();
  84:              #endregion
  85:   
  86:              // ASP.NET 4 - HttpContext.Request.IsSecureConnection
  87:              #region snippet_Secure
  88:              var isSecureConnection = httpContext.Request.IsHttps;
  89:              #endregion
  90:   
  91:              // ASP.NET 4 - HttpContext.Request.UserHostAddress
  92:              #region snippet_Host
  93:              var userHostAddress = httpContext.Connection.RemoteIpAddress?.ToString();
  94:              #endregion
  95:   
  96:              // ASP.NET 4 - HttpContext.Request.Cookies 
  97:              #region snippet_Cookies
  98:              IRequestCookieCollection cookies = httpContext.Request.Cookies;
  99:              string unknownCookieValue = cookies["unknownCookie"]; // will be null (no exception)
 100:              string knownCookieValue = cookies["cookie1name"];     // will be actual value
 101:              #endregion
 102:   
 103:              // ASP.NET 4 - HttpContext.Request.RequestContext.RouteData
 104:              // using Microsoft.AspNetCore.Routing;
 105:              #region snippet_Route
 106:              var routeValue = httpContext.GetRouteValue("key");
 107:              #endregion
 108:   
 109:              // ASP.NET 4 - HttpContext.Request.Headers
 110:              #region snippet_Headers
 111:              // using Microsoft.AspNetCore.Http.Headers;
 112:              // using Microsoft.Net.Http.Headers;
 113:   
 114:              IHeaderDictionary headersDictionary = httpContext.Request.Headers;
 115:   
 116:              // GetTypedHeaders extension method provides strongly typed access to many headers
 117:              var requestHeaders = httpContext.Request.GetTypedHeaders();
 118:              CacheControlHeaderValue cacheControlHeaderValue = requestHeaders.CacheControl;
 119:   
 120:              // For unknown header, unknownheaderValues has zero items and unknownheaderValue is ""
 121:              IList<string> unknownheaderValues = headersDictionary["unknownheader"];
 122:              string unknownheaderValue = headersDictionary["unknownheader"].ToString();
 123:   
 124:              // For known header, knownheaderValues has 1 item and knownheaderValue is the value
 125:              IList<string> knownheaderValues = headersDictionary[HeaderNames.AcceptLanguage];
 126:              string knownheaderValue = headersDictionary[HeaderNames.AcceptLanguage].ToString();
 127:              #endregion
 128:   
 129:              // ASP.NET 4 - HttpContext.Request.UserAgent
 130:              #region snippet_Agent
 131:              string userAgent = headersDictionary[HeaderNames.UserAgent].ToString();
 132:              #endregion
 133:   
 134:              // ASP.NET 4 - HttpContext.Request.UrlReferrer
 135:              #region snippet_Referrer
 136:              string urlReferrer = headersDictionary[HeaderNames.Referer].ToString();
 137:              #endregion
 138:   
 139:              // ASP.NET 4 - HttpContext.Request.ContentType 
 140:              #region snippet_Type
 141:              // using Microsoft.Net.Http.Headers;
 142:   
 143:              MediaTypeHeaderValue mediaHeaderValue = requestHeaders.ContentType;
 144:              string contentType = mediaHeaderValue?.MediaType;   // ex. application/x-www-form-urlencoded
 145:              string contentMainType = mediaHeaderValue?.Type;    // ex. application
 146:              string contentSubType = mediaHeaderValue?.SubType;  // ex. x-www-form-urlencoded
 147:   
 148:              System.Text.Encoding requestEncoding = mediaHeaderValue?.Encoding;
 149:              #endregion
 150:   
 151:              // ASP.NET 4 - HttpContext.Request.Form 
 152:              #region snippet_Form
 153:              if (httpContext.Request.HasFormContentType)
 154:              {
 155:                  IFormCollection form;
 156:   
 157:                  form = httpContext.Request.Form; // sync
 158:                  // Or
 159:                  form = await httpContext.Request.ReadFormAsync(); // async
 160:   
 161:                  string firstName = form["firstname"];
 162:                  string lastName = form["lastname"];
 163:              }
 164:              #endregion
 165:   
 166:              // ----------
 167:              // See 
 168:              // http://stackoverflow.com/questions/31389781/read-body-twice-in-asp-net-5/
 169:   
 170:              // ASP.NET 4 - HttpContext.Request.InputStream
 171:              // Unlike reading the form, reading the raw body is not from a buffer.
 172:              // So you can only do this once per request.
 173:              // 
 174:              // If you need to read the body multiple times per request, see
 175:              // http://stackoverflow.com/questions/31389781/read-body-twice-in-asp-net-5/
 176:   
 177:              #region snippet_Input
 178:              string inputBody;
 179:              using (var reader = new System.IO.StreamReader(
 180:                  httpContext.Request.Body, System.Text.Encoding.UTF8))
 181:              {
 182:                  inputBody = reader.ReadToEnd();
 183:              }
 184:              #endregion
 185:   
 186:              // Use this middleware as a handler, so no call to 
 187:              // await _next.Invoke(aspnetCoreHttpContext);
 188:   
 189:              // ==================================================================
 190:              // Response
 191:   
 192:              // ASP.NET 4 - HttpContext.Response.Status  
 193:              // ASP.NET 4 - HttpContext.Response.StatusDescription (obsolete, removed from HTTP/2) 
 194:              #region snippet_Status
 195:              // using Microsoft.AspNetCore.Http;
 196:              httpContext.Response.StatusCode = StatusCodes.Status200OK;
 197:              #endregion
 198:   
 199:              // ASP.NET 4 - HttpContext.Response.ContentEncoding and HttpContext.Response.ContentType  
 200:              #region snippet_RespType
 201:              // using Microsoft.Net.Http.Headers;
 202:              var mediaType = new MediaTypeHeaderValue("application/json");
 203:              mediaType.Encoding = System.Text.Encoding.UTF8;
 204:              httpContext.Response.ContentType = mediaType.ToString();
 205:              #endregion
 206:   
 207:              // ASP.NET 4 - HttpContext.Response.ContentType only 
 208:              #region snippet_RespTypeOnly
 209:              httpContext.Response.ContentType = "text/html";
 210:              #endregion
 211:   
 212:              // ASP.NET 4 - HttpContext.Response.Output  
 213:              #region  snippet_Output
 214:              string responseContent = GetResponseContent();
 215:              await httpContext.Response.WriteAsync(responseContent);
 216:              #endregion
 217:          }
 218:   
 219:          #region snippet_SetHeaders
 220:          // using Microsoft.AspNet.Http.Headers;
 221:          // using Microsoft.Net.Http.Headers;
 222:   
 223:          private Task SetHeaders(object context)
 224:          {
 225:              var httpContext = (HttpContext)context;
 226:   
 227:              // Set header with single value
 228:              httpContext.Response.Headers["ResponseHeaderName"] = "headerValue";
 229:   
 230:              // Set header with multiple values
 231:              string[] responseHeaderValues = new string[] { "headerValue1", "headerValue1" };
 232:              httpContext.Response.Headers["ResponseHeaderName"] = responseHeaderValues;
 233:   
 234:              // Translating ASP.NET 4's HttpContext.Response.RedirectLocation  
 235:              httpContext.Response.Headers[HeaderNames.Location] = "http://www.example.com";
 236:              // Or
 237:              httpContext.Response.Redirect("http://www.example.com");
 238:   
 239:              // GetTypedHeaders extension method provides strongly typed access to many headers
 240:              var responseHeaders = httpContext.Response.GetTypedHeaders();
 241:   
 242:              // Translating ASP.NET 4's HttpContext.Response.CacheControl 
 243:              responseHeaders.CacheControl = new CacheControlHeaderValue
 244:              {
 245:                  MaxAge = new System.TimeSpan(365, 0, 0, 0)
 246:                  // Many more properties available 
 247:              };
 248:   
 249:              // If you use .Net 4.6+, Task.CompletedTask will be a bit faster
 250:              return Task.FromResult(0);
 251:          }
 252:          #endregion
 253:   
 254:          #region snippet_SetCookies
 255:          private Task SetCookies(object context)
 256:          {
 257:              var httpContext = (HttpContext)context;
 258:   
 259:              IResponseCookies responseCookies = httpContext.Response.Cookies;
 260:   
 261:              responseCookies.Append("cookie1name", "cookie1value");
 262:              responseCookies.Append("cookie2name", "cookie2value",
 263:                  new CookieOptions { Expires = System.DateTime.Now.AddDays(5), HttpOnly = true });
 264:   
 265:              // If you use .Net 4.6+, Task.CompletedTask will be a bit faster
 266:              return Task.FromResult(0); 
 267:          }
 268:          #endregion
 269:   
 270:          // You would normally use MVC to generate HTML like this.
 271:          private string GetResponseContent()
 272:          {
 273:              return @"
 274:  <!DOCTYPE html>
 275:  <html lang=""en"">
 276:  <head>
 277:      <title>index</title>
 278:  </head>
 279:  <body>
 280:  <form action=""form.context"" method=""post"">
 281:      <input type=""text"" name=""firstname"">
 282:      <input type=""text"" name=""lastname"">
 283:      <input type=""submit"" value=""Submit"">
 284:  </form> 
 285:  </body>
 286:  </html>
 287:  ";
 288:          }
 289:      }
 290:   
 291:      public static class HttpContextDemoMiddlewareExtensions
 292:      {
 293:          public static IApplicationBuilder UseHttpContextDemoMiddleware(this IApplicationBuilder builder)
 294:          {
 295:              return builder.UseMiddleware<HttpContextDemoMiddleware>();
 296:          }
 297:      }
 298:  }

HttpContext.Request

HttpContext.Request.HttpMethod translates to:

[!code-csharpMain]

   1:  using Microsoft.AspNetCore.Builder;
   2:  using Microsoft.AspNetCore.Http;
   3:  using System.Collections.Generic;
   4:  using System.Threading.Tasks;
   5:  using Microsoft.Net.Http.Headers;
   6:  using Microsoft.AspNetCore.Http.Extensions;
   7:  using Microsoft.AspNetCore.Routing;
   8:   
   9:  namespace MyApp.Middleware
  10:  {
  11:      public class HttpContextDemoMiddleware
  12:      {
  13:          private readonly RequestDelegate _next;
  14:   
  15:          public HttpContextDemoMiddleware(RequestDelegate next)
  16:          {
  17:              _next = next;
  18:          }
  19:   
  20:          public async Task Invoke(HttpContext httpContext)
  21:          {
  22:              // OnStarting handlers have to be set early during request processing,
  23:              // even though they are used to create the response.
  24:   
  25:              // ----------------------
  26:              // ASP.NET 4 - HttpContext.Response.Headers  
  27:              // ASP.NET 4 - HttpContext.Response.Cookies  
  28:              // 
  29:              // Issue with all response headers is that they will not be sent 
  30:              // after anything has been written to the response body.
  31:              // To solve this, use OnStarting to set a callback that will be called 
  32:              // right before headers are sent. Set the headers in that callback.
  33:              //
  34:              // Setting a cookie results in a Set-Cookie response header.
  35:              // So use an OnStarting handler here as well.
  36:   
  37:              //>40
  38:              httpContext.Response.OnStarting(SetHeaders, state: httpContext);
  39:              httpContext.Response.OnStarting(SetCookies, state: httpContext);
  40:              //<40
  41:   
  42:              // ==================================================================
  43:              // Context
  44:   
  45:              // Unique request ID (no ASP.NET 4 counterpart)
  46:              #region snippet_Trace
  47:              string requestId = httpContext.TraceIdentifier;
  48:              #endregion
  49:   
  50:              // ASP.NET 4 - HttpContext.Items
  51:              #region snippet_Items
  52:              IDictionary<object, object> items = httpContext.Items;
  53:              #endregion
  54:   
  55:              // ==================================================================
  56:              // Request
  57:   
  58:              // ASP.NET 4 - HttpContext.Request.HttpMethod
  59:              #region snippet_Method
  60:              string httpMethod = httpContext.Request.Method;
  61:              #endregion
  62:   
  63:              // ----------
  64:   
  65:              // ASP.NET 4 - HttpContext.Request.QueryString
  66:              #region snippet_Query
  67:              IQueryCollection queryParameters = httpContext.Request.Query;
  68:   
  69:              // If no query parameter "key" used, values will have 0 items
  70:              // If single value used for a key (...?key=v1), values will have 1 item ("v1")
  71:              // If key has multiple values (...?key=v1&key=v2), values will have 2 items ("v1" and "v2")
  72:              IList<string> values = queryParameters["key"];
  73:   
  74:              // If no query parameter "key" used, value will be ""
  75:              // If single value used for a key (...?key=v1), value will be "v1"
  76:              // If key has multiple values (...?key=v1&key=v2), value will be "v1,v2"
  77:              string value = queryParameters["key"].ToString();
  78:              #endregion
  79:   
  80:              // ASP.NET 4 - HttpContext.Request.Url and HttpContext.Request.RawUrl
  81:              #region snippet_Url
  82:              // using Microsoft.AspNetCore.Http.Extensions;
  83:              var url = httpContext.Request.GetDisplayUrl();
  84:              #endregion
  85:   
  86:              // ASP.NET 4 - HttpContext.Request.IsSecureConnection
  87:              #region snippet_Secure
  88:              var isSecureConnection = httpContext.Request.IsHttps;
  89:              #endregion
  90:   
  91:              // ASP.NET 4 - HttpContext.Request.UserHostAddress
  92:              #region snippet_Host
  93:              var userHostAddress = httpContext.Connection.RemoteIpAddress?.ToString();
  94:              #endregion
  95:   
  96:              // ASP.NET 4 - HttpContext.Request.Cookies 
  97:              #region snippet_Cookies
  98:              IRequestCookieCollection cookies = httpContext.Request.Cookies;
  99:              string unknownCookieValue = cookies["unknownCookie"]; // will be null (no exception)
 100:              string knownCookieValue = cookies["cookie1name"];     // will be actual value
 101:              #endregion
 102:   
 103:              // ASP.NET 4 - HttpContext.Request.RequestContext.RouteData
 104:              // using Microsoft.AspNetCore.Routing;
 105:              #region snippet_Route
 106:              var routeValue = httpContext.GetRouteValue("key");
 107:              #endregion
 108:   
 109:              // ASP.NET 4 - HttpContext.Request.Headers
 110:              #region snippet_Headers
 111:              // using Microsoft.AspNetCore.Http.Headers;
 112:              // using Microsoft.Net.Http.Headers;
 113:   
 114:              IHeaderDictionary headersDictionary = httpContext.Request.Headers;
 115:   
 116:              // GetTypedHeaders extension method provides strongly typed access to many headers
 117:              var requestHeaders = httpContext.Request.GetTypedHeaders();
 118:              CacheControlHeaderValue cacheControlHeaderValue = requestHeaders.CacheControl;
 119:   
 120:              // For unknown header, unknownheaderValues has zero items and unknownheaderValue is ""
 121:              IList<string> unknownheaderValues = headersDictionary["unknownheader"];
 122:              string unknownheaderValue = headersDictionary["unknownheader"].ToString();
 123:   
 124:              // For known header, knownheaderValues has 1 item and knownheaderValue is the value
 125:              IList<string> knownheaderValues = headersDictionary[HeaderNames.AcceptLanguage];
 126:              string knownheaderValue = headersDictionary[HeaderNames.AcceptLanguage].ToString();
 127:              #endregion
 128:   
 129:              // ASP.NET 4 - HttpContext.Request.UserAgent
 130:              #region snippet_Agent
 131:              string userAgent = headersDictionary[HeaderNames.UserAgent].ToString();
 132:              #endregion
 133:   
 134:              // ASP.NET 4 - HttpContext.Request.UrlReferrer
 135:              #region snippet_Referrer
 136:              string urlReferrer = headersDictionary[HeaderNames.Referer].ToString();
 137:              #endregion
 138:   
 139:              // ASP.NET 4 - HttpContext.Request.ContentType 
 140:              #region snippet_Type
 141:              // using Microsoft.Net.Http.Headers;
 142:   
 143:              MediaTypeHeaderValue mediaHeaderValue = requestHeaders.ContentType;
 144:              string contentType = mediaHeaderValue?.MediaType;   // ex. application/x-www-form-urlencoded
 145:              string contentMainType = mediaHeaderValue?.Type;    // ex. application
 146:              string contentSubType = mediaHeaderValue?.SubType;  // ex. x-www-form-urlencoded
 147:   
 148:              System.Text.Encoding requestEncoding = mediaHeaderValue?.Encoding;
 149:              #endregion
 150:   
 151:              // ASP.NET 4 - HttpContext.Request.Form 
 152:              #region snippet_Form
 153:              if (httpContext.Request.HasFormContentType)
 154:              {
 155:                  IFormCollection form;
 156:   
 157:                  form = httpContext.Request.Form; // sync
 158:                  // Or
 159:                  form = await httpContext.Request.ReadFormAsync(); // async
 160:   
 161:                  string firstName = form["firstname"];
 162:                  string lastName = form["lastname"];
 163:              }
 164:              #endregion
 165:   
 166:              // ----------
 167:              // See 
 168:              // http://stackoverflow.com/questions/31389781/read-body-twice-in-asp-net-5/
 169:   
 170:              // ASP.NET 4 - HttpContext.Request.InputStream
 171:              // Unlike reading the form, reading the raw body is not from a buffer.
 172:              // So you can only do this once per request.
 173:              // 
 174:              // If you need to read the body multiple times per request, see
 175:              // http://stackoverflow.com/questions/31389781/read-body-twice-in-asp-net-5/
 176:   
 177:              #region snippet_Input
 178:              string inputBody;
 179:              using (var reader = new System.IO.StreamReader(
 180:                  httpContext.Request.Body, System.Text.Encoding.UTF8))
 181:              {
 182:                  inputBody = reader.ReadToEnd();
 183:              }
 184:              #endregion
 185:   
 186:              // Use this middleware as a handler, so no call to 
 187:              // await _next.Invoke(aspnetCoreHttpContext);
 188:   
 189:              // ==================================================================
 190:              // Response
 191:   
 192:              // ASP.NET 4 - HttpContext.Response.Status  
 193:              // ASP.NET 4 - HttpContext.Response.StatusDescription (obsolete, removed from HTTP/2) 
 194:              #region snippet_Status
 195:              // using Microsoft.AspNetCore.Http;
 196:              httpContext.Response.StatusCode = StatusCodes.Status200OK;
 197:              #endregion
 198:   
 199:              // ASP.NET 4 - HttpContext.Response.ContentEncoding and HttpContext.Response.ContentType  
 200:              #region snippet_RespType
 201:              // using Microsoft.Net.Http.Headers;
 202:              var mediaType = new MediaTypeHeaderValue("application/json");
 203:              mediaType.Encoding = System.Text.Encoding.UTF8;
 204:              httpContext.Response.ContentType = mediaType.ToString();
 205:              #endregion
 206:   
 207:              // ASP.NET 4 - HttpContext.Response.ContentType only 
 208:              #region snippet_RespTypeOnly
 209:              httpContext.Response.ContentType = "text/html";
 210:              #endregion
 211:   
 212:              // ASP.NET 4 - HttpContext.Response.Output  
 213:              #region  snippet_Output
 214:              string responseContent = GetResponseContent();
 215:              await httpContext.Response.WriteAsync(responseContent);
 216:              #endregion
 217:          }
 218:   
 219:          #region snippet_SetHeaders
 220:          // using Microsoft.AspNet.Http.Headers;
 221:          // using Microsoft.Net.Http.Headers;
 222:   
 223:          private Task SetHeaders(object context)
 224:          {
 225:              var httpContext = (HttpContext)context;
 226:   
 227:              // Set header with single value
 228:              httpContext.Response.Headers["ResponseHeaderName"] = "headerValue";
 229:   
 230:              // Set header with multiple values
 231:              string[] responseHeaderValues = new string[] { "headerValue1", "headerValue1" };
 232:              httpContext.Response.Headers["ResponseHeaderName"] = responseHeaderValues;
 233:   
 234:              // Translating ASP.NET 4's HttpContext.Response.RedirectLocation  
 235:              httpContext.Response.Headers[HeaderNames.Location] = "http://www.example.com";
 236:              // Or
 237:              httpContext.Response.Redirect("http://www.example.com");
 238:   
 239:              // GetTypedHeaders extension method provides strongly typed access to many headers
 240:              var responseHeaders = httpContext.Response.GetTypedHeaders();
 241:   
 242:              // Translating ASP.NET 4's HttpContext.Response.CacheControl 
 243:              responseHeaders.CacheControl = new CacheControlHeaderValue
 244:              {
 245:                  MaxAge = new System.TimeSpan(365, 0, 0, 0)
 246:                  // Many more properties available 
 247:              };
 248:   
 249:              // If you use .Net 4.6+, Task.CompletedTask will be a bit faster
 250:              return Task.FromResult(0);
 251:          }
 252:          #endregion
 253:   
 254:          #region snippet_SetCookies
 255:          private Task SetCookies(object context)
 256:          {
 257:              var httpContext = (HttpContext)context;
 258:   
 259:              IResponseCookies responseCookies = httpContext.Response.Cookies;
 260:   
 261:              responseCookies.Append("cookie1name", "cookie1value");
 262:              responseCookies.Append("cookie2name", "cookie2value",
 263:                  new CookieOptions { Expires = System.DateTime.Now.AddDays(5), HttpOnly = true });
 264:   
 265:              // If you use .Net 4.6+, Task.CompletedTask will be a bit faster
 266:              return Task.FromResult(0); 
 267:          }
 268:          #endregion
 269:   
 270:          // You would normally use MVC to generate HTML like this.
 271:          private string GetResponseContent()
 272:          {
 273:              return @"
 274:  <!DOCTYPE html>
 275:  <html lang=""en"">
 276:  <head>
 277:      <title>index</title>
 278:  </head>
 279:  <body>
 280:  <form action=""form.context"" method=""post"">
 281:      <input type=""text"" name=""firstname"">
 282:      <input type=""text"" name=""lastname"">
 283:      <input type=""submit"" value=""Submit"">
 284:  </form> 
 285:  </body>
 286:  </html>
 287:  ";
 288:          }
 289:      }
 290:   
 291:      public static class HttpContextDemoMiddlewareExtensions
 292:      {
 293:          public static IApplicationBuilder UseHttpContextDemoMiddleware(this IApplicationBuilder builder)
 294:          {
 295:              return builder.UseMiddleware<HttpContextDemoMiddleware>();
 296:          }
 297:      }
 298:  }

HttpContext.Request.QueryString translates to:

[!code-csharpMain]

   1:  using Microsoft.AspNetCore.Builder;
   2:  using Microsoft.AspNetCore.Http;
   3:  using System.Collections.Generic;
   4:  using System.Threading.Tasks;
   5:  using Microsoft.Net.Http.Headers;
   6:  using Microsoft.AspNetCore.Http.Extensions;
   7:  using Microsoft.AspNetCore.Routing;
   8:   
   9:  namespace MyApp.Middleware
  10:  {
  11:      public class HttpContextDemoMiddleware
  12:      {
  13:          private readonly RequestDelegate _next;
  14:   
  15:          public HttpContextDemoMiddleware(RequestDelegate next)
  16:          {
  17:              _next = next;
  18:          }
  19:   
  20:          public async Task Invoke(HttpContext httpContext)
  21:          {
  22:              // OnStarting handlers have to be set early during request processing,
  23:              // even though they are used to create the response.
  24:   
  25:              // ----------------------
  26:              // ASP.NET 4 - HttpContext.Response.Headers  
  27:              // ASP.NET 4 - HttpContext.Response.Cookies  
  28:              // 
  29:              // Issue with all response headers is that they will not be sent 
  30:              // after anything has been written to the response body.
  31:              // To solve this, use OnStarting to set a callback that will be called 
  32:              // right before headers are sent. Set the headers in that callback.
  33:              //
  34:              // Setting a cookie results in a Set-Cookie response header.
  35:              // So use an OnStarting handler here as well.
  36:   
  37:              //>40
  38:              httpContext.Response.OnStarting(SetHeaders, state: httpContext);
  39:              httpContext.Response.OnStarting(SetCookies, state: httpContext);
  40:              //<40
  41:   
  42:              // ==================================================================
  43:              // Context
  44:   
  45:              // Unique request ID (no ASP.NET 4 counterpart)
  46:              #region snippet_Trace
  47:              string requestId = httpContext.TraceIdentifier;
  48:              #endregion
  49:   
  50:              // ASP.NET 4 - HttpContext.Items
  51:              #region snippet_Items
  52:              IDictionary<object, object> items = httpContext.Items;
  53:              #endregion
  54:   
  55:              // ==================================================================
  56:              // Request
  57:   
  58:              // ASP.NET 4 - HttpContext.Request.HttpMethod
  59:              #region snippet_Method
  60:              string httpMethod = httpContext.Request.Method;
  61:              #endregion
  62:   
  63:              // ----------
  64:   
  65:              // ASP.NET 4 - HttpContext.Request.QueryString
  66:              #region snippet_Query
  67:              IQueryCollection queryParameters = httpContext.Request.Query;
  68:   
  69:              // If no query parameter "key" used, values will have 0 items
  70:              // If single value used for a key (...?key=v1), values will have 1 item ("v1")
  71:              // If key has multiple values (...?key=v1&key=v2), values will have 2 items ("v1" and "v2")
  72:              IList<string> values = queryParameters["key"];
  73:   
  74:              // If no query parameter "key" used, value will be ""
  75:              // If single value used for a key (...?key=v1), value will be "v1"
  76:              // If key has multiple values (...?key=v1&key=v2), value will be "v1,v2"
  77:              string value = queryParameters["key"].ToString();
  78:              #endregion
  79:   
  80:              // ASP.NET 4 - HttpContext.Request.Url and HttpContext.Request.RawUrl
  81:              #region snippet_Url
  82:              // using Microsoft.AspNetCore.Http.Extensions;
  83:              var url = httpContext.Request.GetDisplayUrl();
  84:              #endregion
  85:   
  86:              // ASP.NET 4 - HttpContext.Request.IsSecureConnection
  87:              #region snippet_Secure
  88:              var isSecureConnection = httpContext.Request.IsHttps;
  89:              #endregion
  90:   
  91:              // ASP.NET 4 - HttpContext.Request.UserHostAddress
  92:              #region snippet_Host
  93:              var userHostAddress = httpContext.Connection.RemoteIpAddress?.ToString();
  94:              #endregion
  95:   
  96:              // ASP.NET 4 - HttpContext.Request.Cookies 
  97:              #region snippet_Cookies
  98:              IRequestCookieCollection cookies = httpContext.Request.Cookies;
  99:              string unknownCookieValue = cookies["unknownCookie"]; // will be null (no exception)
 100:              string knownCookieValue = cookies["cookie1name"];     // will be actual value
 101:              #endregion
 102:   
 103:              // ASP.NET 4 - HttpContext.Request.RequestContext.RouteData
 104:              // using Microsoft.AspNetCore.Routing;
 105:              #region snippet_Route
 106:              var routeValue = httpContext.GetRouteValue("key");
 107:              #endregion
 108:   
 109:              // ASP.NET 4 - HttpContext.Request.Headers
 110:              #region snippet_Headers
 111:              // using Microsoft.AspNetCore.Http.Headers;
 112:              // using Microsoft.Net.Http.Headers;
 113:   
 114:              IHeaderDictionary headersDictionary = httpContext.Request.Headers;
 115:   
 116:              // GetTypedHeaders extension method provides strongly typed access to many headers
 117:              var requestHeaders = httpContext.Request.GetTypedHeaders();
 118:              CacheControlHeaderValue cacheControlHeaderValue = requestHeaders.CacheControl;
 119:   
 120:              // For unknown header, unknownheaderValues has zero items and unknownheaderValue is ""
 121:              IList<string> unknownheaderValues = headersDictionary["unknownheader"];
 122:              string unknownheaderValue = headersDictionary["unknownheader"].ToString();
 123:   
 124:              // For known header, knownheaderValues has 1 item and knownheaderValue is the value
 125:              IList<string> knownheaderValues = headersDictionary[HeaderNames.AcceptLanguage];
 126:              string knownheaderValue = headersDictionary[HeaderNames.AcceptLanguage].ToString();
 127:              #endregion
 128:   
 129:              // ASP.NET 4 - HttpContext.Request.UserAgent
 130:              #region snippet_Agent
 131:              string userAgent = headersDictionary[HeaderNames.UserAgent].ToString();
 132:              #endregion
 133:   
 134:              // ASP.NET 4 - HttpContext.Request.UrlReferrer
 135:              #region snippet_Referrer
 136:              string urlReferrer = headersDictionary[HeaderNames.Referer].ToString();
 137:              #endregion
 138:   
 139:              // ASP.NET 4 - HttpContext.Request.ContentType 
 140:              #region snippet_Type
 141:              // using Microsoft.Net.Http.Headers;
 142:   
 143:              MediaTypeHeaderValue mediaHeaderValue = requestHeaders.ContentType;
 144:              string contentType = mediaHeaderValue?.MediaType;   // ex. application/x-www-form-urlencoded
 145:              string contentMainType = mediaHeaderValue?.Type;    // ex. application
 146:              string contentSubType = mediaHeaderValue?.SubType;  // ex. x-www-form-urlencoded
 147:   
 148:              System.Text.Encoding requestEncoding = mediaHeaderValue?.Encoding;
 149:              #endregion
 150:   
 151:              // ASP.NET 4 - HttpContext.Request.Form 
 152:              #region snippet_Form
 153:              if (httpContext.Request.HasFormContentType)
 154:              {
 155:                  IFormCollection form;
 156:   
 157:                  form = httpContext.Request.Form; // sync
 158:                  // Or
 159:                  form = await httpContext.Request.ReadFormAsync(); // async
 160:   
 161:                  string firstName = form["firstname"];
 162:                  string lastName = form["lastname"];
 163:              }
 164:              #endregion
 165:   
 166:              // ----------
 167:              // See 
 168:              // http://stackoverflow.com/questions/31389781/read-body-twice-in-asp-net-5/
 169:   
 170:              // ASP.NET 4 - HttpContext.Request.InputStream
 171:              // Unlike reading the form, reading the raw body is not from a buffer.
 172:              // So you can only do this once per request.
 173:              // 
 174:              // If you need to read the body multiple times per request, see
 175:              // http://stackoverflow.com/questions/31389781/read-body-twice-in-asp-net-5/
 176:   
 177:              #region snippet_Input
 178:              string inputBody;
 179:              using (var reader = new System.IO.StreamReader(
 180:                  httpContext.Request.Body, System.Text.Encoding.UTF8))
 181:              {
 182:                  inputBody = reader.ReadToEnd();
 183:              }
 184:              #endregion
 185:   
 186:              // Use this middleware as a handler, so no call to 
 187:              // await _next.Invoke(aspnetCoreHttpContext);
 188:   
 189:              // ==================================================================
 190:              // Response
 191:   
 192:              // ASP.NET 4 - HttpContext.Response.Status  
 193:              // ASP.NET 4 - HttpContext.Response.StatusDescription (obsolete, removed from HTTP/2) 
 194:              #region snippet_Status
 195:              // using Microsoft.AspNetCore.Http;
 196:              httpContext.Response.StatusCode = StatusCodes.Status200OK;
 197:              #endregion
 198:   
 199:              // ASP.NET 4 - HttpContext.Response.ContentEncoding and HttpContext.Response.ContentType  
 200:              #region snippet_RespType
 201:              // using Microsoft.Net.Http.Headers;
 202:              var mediaType = new MediaTypeHeaderValue("application/json");
 203:              mediaType.Encoding = System.Text.Encoding.UTF8;
 204:              httpContext.Response.ContentType = mediaType.ToString();
 205:              #endregion
 206:   
 207:              // ASP.NET 4 - HttpContext.Response.ContentType only 
 208:              #region snippet_RespTypeOnly
 209:              httpContext.Response.ContentType = "text/html";
 210:              #endregion
 211:   
 212:              // ASP.NET 4 - HttpContext.Response.Output  
 213:              #region  snippet_Output
 214:              string responseContent = GetResponseContent();
 215:              await httpContext.Response.WriteAsync(responseContent);
 216:              #endregion
 217:          }
 218:   
 219:          #region snippet_SetHeaders
 220:          // using Microsoft.AspNet.Http.Headers;
 221:          // using Microsoft.Net.Http.Headers;
 222:   
 223:          private Task SetHeaders(object context)
 224:          {
 225:              var httpContext = (HttpContext)context;
 226:   
 227:              // Set header with single value
 228:              httpContext.Response.Headers["ResponseHeaderName"] = "headerValue";
 229:   
 230:              // Set header with multiple values
 231:              string[] responseHeaderValues = new string[] { "headerValue1", "headerValue1" };
 232:              httpContext.Response.Headers["ResponseHeaderName"] = responseHeaderValues;
 233:   
 234:              // Translating ASP.NET 4's HttpContext.Response.RedirectLocation  
 235:              httpContext.Response.Headers[HeaderNames.Location] = "http://www.example.com";
 236:              // Or
 237:              httpContext.Response.Redirect("http://www.example.com");
 238:   
 239:              // GetTypedHeaders extension method provides strongly typed access to many headers
 240:              var responseHeaders = httpContext.Response.GetTypedHeaders();
 241:   
 242:              // Translating ASP.NET 4's HttpContext.Response.CacheControl 
 243:              responseHeaders.CacheControl = new CacheControlHeaderValue
 244:              {
 245:                  MaxAge = new System.TimeSpan(365, 0, 0, 0)
 246:                  // Many more properties available 
 247:              };
 248:   
 249:              // If you use .Net 4.6+, Task.CompletedTask will be a bit faster
 250:              return Task.FromResult(0);
 251:          }
 252:          #endregion
 253:   
 254:          #region snippet_SetCookies
 255:          private Task SetCookies(object context)
 256:          {
 257:              var httpContext = (HttpContext)context;
 258:   
 259:              IResponseCookies responseCookies = httpContext.Response.Cookies;
 260:   
 261:              responseCookies.Append("cookie1name", "cookie1value");
 262:              responseCookies.Append("cookie2name", "cookie2value",
 263:                  new CookieOptions { Expires = System.DateTime.Now.AddDays(5), HttpOnly = true });
 264:   
 265:              // If you use .Net 4.6+, Task.CompletedTask will be a bit faster
 266:              return Task.FromResult(0); 
 267:          }
 268:          #endregion
 269:   
 270:          // You would normally use MVC to generate HTML like this.
 271:          private string GetResponseContent()
 272:          {
 273:              return @"
 274:  <!DOCTYPE html>
 275:  <html lang=""en"">
 276:  <head>
 277:      <title>index</title>
 278:  </head>
 279:  <body>
 280:  <form action=""form.context"" method=""post"">
 281:      <input type=""text"" name=""firstname"">
 282:      <input type=""text"" name=""lastname"">
 283:      <input type=""submit"" value=""Submit"">
 284:  </form> 
 285:  </body>
 286:  </html>
 287:  ";
 288:          }
 289:      }
 290:   
 291:      public static class HttpContextDemoMiddlewareExtensions
 292:      {
 293:          public static IApplicationBuilder UseHttpContextDemoMiddleware(this IApplicationBuilder builder)
 294:          {
 295:              return builder.UseMiddleware<HttpContextDemoMiddleware>();
 296:          }
 297:      }
 298:  }

HttpContext.Request.Url and HttpContext.Request.RawUrl translate to:

[!code-csharpMain]

   1:  using Microsoft.AspNetCore.Builder;
   2:  using Microsoft.AspNetCore.Http;
   3:  using System.Collections.Generic;
   4:  using System.Threading.Tasks;
   5:  using Microsoft.Net.Http.Headers;
   6:  using Microsoft.AspNetCore.Http.Extensions;
   7:  using Microsoft.AspNetCore.Routing;
   8:   
   9:  namespace MyApp.Middleware
  10:  {
  11:      public class HttpContextDemoMiddleware
  12:      {
  13:          private readonly RequestDelegate _next;
  14:   
  15:          public HttpContextDemoMiddleware(RequestDelegate next)
  16:          {
  17:              _next = next;
  18:          }
  19:   
  20:          public async Task Invoke(HttpContext httpContext)
  21:          {
  22:              // OnStarting handlers have to be set early during request processing,
  23:              // even though they are used to create the response.
  24:   
  25:              // ----------------------
  26:              // ASP.NET 4 - HttpContext.Response.Headers  
  27:              // ASP.NET 4 - HttpContext.Response.Cookies  
  28:              // 
  29:              // Issue with all response headers is that they will not be sent 
  30:              // after anything has been written to the response body.
  31:              // To solve this, use OnStarting to set a callback that will be called 
  32:              // right before headers are sent. Set the headers in that callback.
  33:              //
  34:              // Setting a cookie results in a Set-Cookie response header.
  35:              // So use an OnStarting handler here as well.
  36:   
  37:              //>40
  38:              httpContext.Response.OnStarting(SetHeaders, state: httpContext);
  39:              httpContext.Response.OnStarting(SetCookies, state: httpContext);
  40:              //<40
  41:   
  42:              // ==================================================================
  43:              // Context
  44:   
  45:              // Unique request ID (no ASP.NET 4 counterpart)
  46:              #region snippet_Trace
  47:              string requestId = httpContext.TraceIdentifier;
  48:              #endregion
  49:   
  50:              // ASP.NET 4 - HttpContext.Items
  51:              #region snippet_Items
  52:              IDictionary<object, object> items = httpContext.Items;
  53:              #endregion
  54:   
  55:              // ==================================================================
  56:              // Request
  57:   
  58:              // ASP.NET 4 - HttpContext.Request.HttpMethod
  59:              #region snippet_Method
  60:              string httpMethod = httpContext.Request.Method;
  61:              #endregion
  62:   
  63:              // ----------
  64:   
  65:              // ASP.NET 4 - HttpContext.Request.QueryString
  66:              #region snippet_Query
  67:              IQueryCollection queryParameters = httpContext.Request.Query;
  68:   
  69:              // If no query parameter "key" used, values will have 0 items
  70:              // If single value used for a key (...?key=v1), values will have 1 item ("v1")
  71:              // If key has multiple values (...?key=v1&key=v2), values will have 2 items ("v1" and "v2")
  72:              IList<string> values = queryParameters["key"];
  73:   
  74:              // If no query parameter "key" used, value will be ""
  75:              // If single value used for a key (...?key=v1), value will be "v1"
  76:              // If key has multiple values (...?key=v1&key=v2), value will be "v1,v2"
  77:              string value = queryParameters["key"].ToString();
  78:              #endregion
  79:   
  80:              // ASP.NET 4 - HttpContext.Request.Url and HttpContext.Request.RawUrl
  81:              #region snippet_Url
  82:              // using Microsoft.AspNetCore.Http.Extensions;
  83:              var url = httpContext.Request.GetDisplayUrl();
  84:              #endregion
  85:   
  86:              // ASP.NET 4 - HttpContext.Request.IsSecureConnection
  87:              #region snippet_Secure
  88:              var isSecureConnection = httpContext.Request.IsHttps;
  89:              #endregion
  90:   
  91:              // ASP.NET 4 - HttpContext.Request.UserHostAddress
  92:              #region snippet_Host
  93:              var userHostAddress = httpContext.Connection.RemoteIpAddress?.ToString();
  94:              #endregion
  95:   
  96:              // ASP.NET 4 - HttpContext.Request.Cookies 
  97:              #region snippet_Cookies
  98:              IRequestCookieCollection cookies = httpContext.Request.Cookies;
  99:              string unknownCookieValue = cookies["unknownCookie"]; // will be null (no exception)
 100:              string knownCookieValue = cookies["cookie1name"];     // will be actual value
 101:              #endregion
 102:   
 103:              // ASP.NET 4 - HttpContext.Request.RequestContext.RouteData
 104:              // using Microsoft.AspNetCore.Routing;
 105:              #region snippet_Route
 106:              var routeValue = httpContext.GetRouteValue("key");
 107:              #endregion
 108:   
 109:              // ASP.NET 4 - HttpContext.Request.Headers
 110:              #region snippet_Headers
 111:              // using Microsoft.AspNetCore.Http.Headers;
 112:              // using Microsoft.Net.Http.Headers;
 113:   
 114:              IHeaderDictionary headersDictionary = httpContext.Request.Headers;
 115:   
 116:              // GetTypedHeaders extension method provides strongly typed access to many headers
 117:              var requestHeaders = httpContext.Request.GetTypedHeaders();
 118:              CacheControlHeaderValue cacheControlHeaderValue = requestHeaders.CacheControl;
 119:   
 120:              // For unknown header, unknownheaderValues has zero items and unknownheaderValue is ""
 121:              IList<string> unknownheaderValues = headersDictionary["unknownheader"];
 122:              string unknownheaderValue = headersDictionary["unknownheader"].ToString();
 123:   
 124:              // For known header, knownheaderValues has 1 item and knownheaderValue is the value
 125:              IList<string> knownheaderValues = headersDictionary[HeaderNames.AcceptLanguage];
 126:              string knownheaderValue = headersDictionary[HeaderNames.AcceptLanguage].ToString();
 127:              #endregion
 128:   
 129:              // ASP.NET 4 - HttpContext.Request.UserAgent
 130:              #region snippet_Agent
 131:              string userAgent = headersDictionary[HeaderNames.UserAgent].ToString();
 132:              #endregion
 133:   
 134:              // ASP.NET 4 - HttpContext.Request.UrlReferrer
 135:              #region snippet_Referrer
 136:              string urlReferrer = headersDictionary[HeaderNames.Referer].ToString();
 137:              #endregion
 138:   
 139:              // ASP.NET 4 - HttpContext.Request.ContentType 
 140:              #region snippet_Type
 141:              // using Microsoft.Net.Http.Headers;
 142:   
 143:              MediaTypeHeaderValue mediaHeaderValue = requestHeaders.ContentType;
 144:              string contentType = mediaHeaderValue?.MediaType;   // ex. application/x-www-form-urlencoded
 145:              string contentMainType = mediaHeaderValue?.Type;    // ex. application
 146:              string contentSubType = mediaHeaderValue?.SubType;  // ex. x-www-form-urlencoded
 147:   
 148:              System.Text.Encoding requestEncoding = mediaHeaderValue?.Encoding;
 149:              #endregion
 150:   
 151:              // ASP.NET 4 - HttpContext.Request.Form 
 152:              #region snippet_Form
 153:              if (httpContext.Request.HasFormContentType)
 154:              {
 155:                  IFormCollection form;
 156:   
 157:                  form = httpContext.Request.Form; // sync
 158:                  // Or
 159:                  form = await httpContext.Request.ReadFormAsync(); // async
 160:   
 161:                  string firstName = form["firstname"];
 162:                  string lastName = form["lastname"];
 163:              }
 164:              #endregion
 165:   
 166:              // ----------
 167:              // See 
 168:              // http://stackoverflow.com/questions/31389781/read-body-twice-in-asp-net-5/
 169:   
 170:              // ASP.NET 4 - HttpContext.Request.InputStream
 171:              // Unlike reading the form, reading the raw body is not from a buffer.
 172:              // So you can only do this once per request.
 173:              // 
 174:              // If you need to read the body multiple times per request, see
 175:              // http://stackoverflow.com/questions/31389781/read-body-twice-in-asp-net-5/
 176:   
 177:              #region snippet_Input
 178:              string inputBody;
 179:              using (var reader = new System.IO.StreamReader(
 180:                  httpContext.Request.Body, System.Text.Encoding.UTF8))
 181:              {
 182:                  inputBody = reader.ReadToEnd();
 183:              }
 184:              #endregion
 185:   
 186:              // Use this middleware as a handler, so no call to 
 187:              // await _next.Invoke(aspnetCoreHttpContext);
 188:   
 189:              // ==================================================================
 190:              // Response
 191:   
 192:              // ASP.NET 4 - HttpContext.Response.Status  
 193:              // ASP.NET 4 - HttpContext.Response.StatusDescription (obsolete, removed from HTTP/2) 
 194:              #region snippet_Status
 195:              // using Microsoft.AspNetCore.Http;
 196:              httpContext.Response.StatusCode = StatusCodes.Status200OK;
 197:              #endregion
 198:   
 199:              // ASP.NET 4 - HttpContext.Response.ContentEncoding and HttpContext.Response.ContentType  
 200:              #region snippet_RespType
 201:              // using Microsoft.Net.Http.Headers;
 202:              var mediaType = new MediaTypeHeaderValue("application/json");
 203:              mediaType.Encoding = System.Text.Encoding.UTF8;
 204:              httpContext.Response.ContentType = mediaType.ToString();
 205:              #endregion
 206:   
 207:              // ASP.NET 4 - HttpContext.Response.ContentType only 
 208:              #region snippet_RespTypeOnly
 209:              httpContext.Response.ContentType = "text/html";
 210:              #endregion
 211:   
 212:              // ASP.NET 4 - HttpContext.Response.Output  
 213:              #region  snippet_Output
 214:              string responseContent = GetResponseContent();
 215:              await httpContext.Response.WriteAsync(responseContent);
 216:              #endregion
 217:          }
 218:   
 219:          #region snippet_SetHeaders
 220:          // using Microsoft.AspNet.Http.Headers;
 221:          // using Microsoft.Net.Http.Headers;
 222:   
 223:          private Task SetHeaders(object context)
 224:          {
 225:              var httpContext = (HttpContext)context;
 226:   
 227:              // Set header with single value
 228:              httpContext.Response.Headers["ResponseHeaderName"] = "headerValue";
 229:   
 230:              // Set header with multiple values
 231:              string[] responseHeaderValues = new string[] { "headerValue1", "headerValue1" };
 232:              httpContext.Response.Headers["ResponseHeaderName"] = responseHeaderValues;
 233:   
 234:              // Translating ASP.NET 4's HttpContext.Response.RedirectLocation  
 235:              httpContext.Response.Headers[HeaderNames.Location] = "http://www.example.com";
 236:              // Or
 237:              httpContext.Response.Redirect("http://www.example.com");
 238:   
 239:              // GetTypedHeaders extension method provides strongly typed access to many headers
 240:              var responseHeaders = httpContext.Response.GetTypedHeaders();
 241:   
 242:              // Translating ASP.NET 4's HttpContext.Response.CacheControl 
 243:              responseHeaders.CacheControl = new CacheControlHeaderValue
 244:              {
 245:                  MaxAge = new System.TimeSpan(365, 0, 0, 0)
 246:                  // Many more properties available 
 247:              };
 248:   
 249:              // If you use .Net 4.6+, Task.CompletedTask will be a bit faster
 250:              return Task.FromResult(0);
 251:          }
 252:          #endregion
 253:   
 254:          #region snippet_SetCookies
 255:          private Task SetCookies(object context)
 256:          {
 257:              var httpContext = (HttpContext)context;
 258:   
 259:              IResponseCookies responseCookies = httpContext.Response.Cookies;
 260:   
 261:              responseCookies.Append("cookie1name", "cookie1value");
 262:              responseCookies.Append("cookie2name", "cookie2value",
 263:                  new CookieOptions { Expires = System.DateTime.Now.AddDays(5), HttpOnly = true });
 264:   
 265:              // If you use .Net 4.6+, Task.CompletedTask will be a bit faster
 266:              return Task.FromResult(0); 
 267:          }
 268:          #endregion
 269:   
 270:          // You would normally use MVC to generate HTML like this.
 271:          private string GetResponseContent()
 272:          {
 273:              return @"
 274:  <!DOCTYPE html>
 275:  <html lang=""en"">
 276:  <head>
 277:      <title>index</title>
 278:  </head>
 279:  <body>
 280:  <form action=""form.context"" method=""post"">
 281:      <input type=""text"" name=""firstname"">
 282:      <input type=""text"" name=""lastname"">
 283:      <input type=""submit"" value=""Submit"">
 284:  </form> 
 285:  </body>
 286:  </html>
 287:  ";
 288:          }
 289:      }
 290:   
 291:      public static class HttpContextDemoMiddlewareExtensions
 292:      {
 293:          public static IApplicationBuilder UseHttpContextDemoMiddleware(this IApplicationBuilder builder)
 294:          {
 295:              return builder.UseMiddleware<HttpContextDemoMiddleware>();
 296:          }
 297:      }
 298:  }

HttpContext.Request.IsSecureConnection translates to:

[!code-csharpMain]

   1:  using Microsoft.AspNetCore.Builder;
   2:  using Microsoft.AspNetCore.Http;
   3:  using System.Collections.Generic;
   4:  using System.Threading.Tasks;
   5:  using Microsoft.Net.Http.Headers;
   6:  using Microsoft.AspNetCore.Http.Extensions;
   7:  using Microsoft.AspNetCore.Routing;
   8:   
   9:  namespace MyApp.Middleware
  10:  {
  11:      public class HttpContextDemoMiddleware
  12:      {
  13:          private readonly RequestDelegate _next;
  14:   
  15:          public HttpContextDemoMiddleware(RequestDelegate next)
  16:          {
  17:              _next = next;
  18:          }
  19:   
  20:          public async Task Invoke(HttpContext httpContext)
  21:          {
  22:              // OnStarting handlers have to be set early during request processing,
  23:              // even though they are used to create the response.
  24:   
  25:              // ----------------------
  26:              // ASP.NET 4 - HttpContext.Response.Headers  
  27:              // ASP.NET 4 - HttpContext.Response.Cookies  
  28:              // 
  29:              // Issue with all response headers is that they will not be sent 
  30:              // after anything has been written to the response body.
  31:              // To solve this, use OnStarting to set a callback that will be called 
  32:              // right before headers are sent. Set the headers in that callback.
  33:              //
  34:              // Setting a cookie results in a Set-Cookie response header.
  35:              // So use an OnStarting handler here as well.
  36:   
  37:              //>40
  38:              httpContext.Response.OnStarting(SetHeaders, state: httpContext);
  39:              httpContext.Response.OnStarting(SetCookies, state: httpContext);
  40:              //<40
  41:   
  42:              // ==================================================================
  43:              // Context
  44:   
  45:              // Unique request ID (no ASP.NET 4 counterpart)
  46:              #region snippet_Trace
  47:              string requestId = httpContext.TraceIdentifier;
  48:              #endregion
  49:   
  50:              // ASP.NET 4 - HttpContext.Items
  51:              #region snippet_Items
  52:              IDictionary<object, object> items = httpContext.Items;
  53:              #endregion
  54:   
  55:              // ==================================================================
  56:              // Request
  57:   
  58:              // ASP.NET 4 - HttpContext.Request.HttpMethod
  59:              #region snippet_Method
  60:              string httpMethod = httpContext.Request.Method;
  61:              #endregion
  62:   
  63:              // ----------
  64:   
  65:              // ASP.NET 4 - HttpContext.Request.QueryString
  66:              #region snippet_Query
  67:              IQueryCollection queryParameters = httpContext.Request.Query;
  68:   
  69:              // If no query parameter "key" used, values will have 0 items
  70:              // If single value used for a key (...?key=v1), values will have 1 item ("v1")
  71:              // If key has multiple values (...?key=v1&key=v2), values will have 2 items ("v1" and "v2")
  72:              IList<string> values = queryParameters["key"];
  73:   
  74:              // If no query parameter "key" used, value will be ""
  75:              // If single value used for a key (...?key=v1), value will be "v1"
  76:              // If key has multiple values (...?key=v1&key=v2), value will be "v1,v2"
  77:              string value = queryParameters["key"].ToString();
  78:              #endregion
  79:   
  80:              // ASP.NET 4 - HttpContext.Request.Url and HttpContext.Request.RawUrl
  81:              #region snippet_Url
  82:              // using Microsoft.AspNetCore.Http.Extensions;
  83:              var url = httpContext.Request.GetDisplayUrl();
  84:              #endregion
  85:   
  86:              // ASP.NET 4 - HttpContext.Request.IsSecureConnection
  87:              #region snippet_Secure
  88:              var isSecureConnection = httpContext.Request.IsHttps;
  89:              #endregion
  90:   
  91:              // ASP.NET 4 - HttpContext.Request.UserHostAddress
  92:              #region snippet_Host
  93:              var userHostAddress = httpContext.Connection.RemoteIpAddress?.ToString();
  94:              #endregion
  95:   
  96:              // ASP.NET 4 - HttpContext.Request.Cookies 
  97:              #region snippet_Cookies
  98:              IRequestCookieCollection cookies = httpContext.Request.Cookies;
  99:              string unknownCookieValue = cookies["unknownCookie"]; // will be null (no exception)
 100:              string knownCookieValue = cookies["cookie1name"];     // will be actual value
 101:              #endregion
 102:   
 103:              // ASP.NET 4 - HttpContext.Request.RequestContext.RouteData
 104:              // using Microsoft.AspNetCore.Routing;
 105:              #region snippet_Route
 106:              var routeValue = httpContext.GetRouteValue("key");
 107:              #endregion
 108:   
 109:              // ASP.NET 4 - HttpContext.Request.Headers
 110:              #region snippet_Headers
 111:              // using Microsoft.AspNetCore.Http.Headers;
 112:              // using Microsoft.Net.Http.Headers;
 113:   
 114:              IHeaderDictionary headersDictionary = httpContext.Request.Headers;
 115:   
 116:              // GetTypedHeaders extension method provides strongly typed access to many headers
 117:              var requestHeaders = httpContext.Request.GetTypedHeaders();
 118:              CacheControlHeaderValue cacheControlHeaderValue = requestHeaders.CacheControl;
 119:   
 120:              // For unknown header, unknownheaderValues has zero items and unknownheaderValue is ""
 121:              IList<string> unknownheaderValues = headersDictionary["unknownheader"];
 122:              string unknownheaderValue = headersDictionary["unknownheader"].ToString();
 123:   
 124:              // For known header, knownheaderValues has 1 item and knownheaderValue is the value
 125:              IList<string> knownheaderValues = headersDictionary[HeaderNames.AcceptLanguage];
 126:              string knownheaderValue = headersDictionary[HeaderNames.AcceptLanguage].ToString();
 127:              #endregion
 128:   
 129:              // ASP.NET 4 - HttpContext.Request.UserAgent
 130:              #region snippet_Agent
 131:              string userAgent = headersDictionary[HeaderNames.UserAgent].ToString();
 132:              #endregion
 133:   
 134:              // ASP.NET 4 - HttpContext.Request.UrlReferrer
 135:              #region snippet_Referrer
 136:              string urlReferrer = headersDictionary[HeaderNames.Referer].ToString();
 137:              #endregion
 138:   
 139:              // ASP.NET 4 - HttpContext.Request.ContentType 
 140:              #region snippet_Type
 141:              // using Microsoft.Net.Http.Headers;
 142:   
 143:              MediaTypeHeaderValue mediaHeaderValue = requestHeaders.ContentType;
 144:              string contentType = mediaHeaderValue?.MediaType;   // ex. application/x-www-form-urlencoded
 145:              string contentMainType = mediaHeaderValue?.Type;    // ex. application
 146:              string contentSubType = mediaHeaderValue?.SubType;  // ex. x-www-form-urlencoded
 147:   
 148:              System.Text.Encoding requestEncoding = mediaHeaderValue?.Encoding;
 149:              #endregion
 150:   
 151:              // ASP.NET 4 - HttpContext.Request.Form 
 152:              #region snippet_Form
 153:              if (httpContext.Request.HasFormContentType)
 154:              {
 155:                  IFormCollection form;
 156:   
 157:                  form = httpContext.Request.Form; // sync
 158:                  // Or
 159:                  form = await httpContext.Request.ReadFormAsync(); // async
 160:   
 161:                  string firstName = form["firstname"];
 162:                  string lastName = form["lastname"];
 163:              }
 164:              #endregion
 165:   
 166:              // ----------
 167:              // See 
 168:              // http://stackoverflow.com/questions/31389781/read-body-twice-in-asp-net-5/
 169:   
 170:              // ASP.NET 4 - HttpContext.Request.InputStream
 171:              // Unlike reading the form, reading the raw body is not from a buffer.
 172:              // So you can only do this once per request.
 173:              // 
 174:              // If you need to read the body multiple times per request, see
 175:              // http://stackoverflow.com/questions/31389781/read-body-twice-in-asp-net-5/
 176:   
 177:              #region snippet_Input
 178:              string inputBody;
 179:              using (var reader = new System.IO.StreamReader(
 180:                  httpContext.Request.Body, System.Text.Encoding.UTF8))
 181:              {
 182:                  inputBody = reader.ReadToEnd();
 183:              }
 184:              #endregion
 185:   
 186:              // Use this middleware as a handler, so no call to 
 187:              // await _next.Invoke(aspnetCoreHttpContext);
 188:   
 189:              // ==================================================================
 190:              // Response
 191:   
 192:              // ASP.NET 4 - HttpContext.Response.Status  
 193:              // ASP.NET 4 - HttpContext.Response.StatusDescription (obsolete, removed from HTTP/2) 
 194:              #region snippet_Status
 195:              // using Microsoft.AspNetCore.Http;
 196:              httpContext.Response.StatusCode = StatusCodes.Status200OK;
 197:              #endregion
 198:   
 199:              // ASP.NET 4 - HttpContext.Response.ContentEncoding and HttpContext.Response.ContentType  
 200:              #region snippet_RespType
 201:              // using Microsoft.Net.Http.Headers;
 202:              var mediaType = new MediaTypeHeaderValue("application/json");
 203:              mediaType.Encoding = System.Text.Encoding.UTF8;
 204:              httpContext.Response.ContentType = mediaType.ToString();
 205:              #endregion
 206:   
 207:              // ASP.NET 4 - HttpContext.Response.ContentType only 
 208:              #region snippet_RespTypeOnly
 209:              httpContext.Response.ContentType = "text/html";
 210:              #endregion
 211:   
 212:              // ASP.NET 4 - HttpContext.Response.Output  
 213:              #region  snippet_Output
 214:              string responseContent = GetResponseContent();
 215:              await httpContext.Response.WriteAsync(responseContent);
 216:              #endregion
 217:          }
 218:   
 219:          #region snippet_SetHeaders
 220:          // using Microsoft.AspNet.Http.Headers;
 221:          // using Microsoft.Net.Http.Headers;
 222:   
 223:          private Task SetHeaders(object context)
 224:          {
 225:              var httpContext = (HttpContext)context;
 226:   
 227:              // Set header with single value
 228:              httpContext.Response.Headers["ResponseHeaderName"] = "headerValue";
 229:   
 230:              // Set header with multiple values
 231:              string[] responseHeaderValues = new string[] { "headerValue1", "headerValue1" };
 232:              httpContext.Response.Headers["ResponseHeaderName"] = responseHeaderValues;
 233:   
 234:              // Translating ASP.NET 4's HttpContext.Response.RedirectLocation  
 235:              httpContext.Response.Headers[HeaderNames.Location] = "http://www.example.com";
 236:              // Or
 237:              httpContext.Response.Redirect("http://www.example.com");
 238:   
 239:              // GetTypedHeaders extension method provides strongly typed access to many headers
 240:              var responseHeaders = httpContext.Response.GetTypedHeaders();
 241:   
 242:              // Translating ASP.NET 4's HttpContext.Response.CacheControl 
 243:              responseHeaders.CacheControl = new CacheControlHeaderValue
 244:              {
 245:                  MaxAge = new System.TimeSpan(365, 0, 0, 0)
 246:                  // Many more properties available 
 247:              };
 248:   
 249:              // If you use .Net 4.6+, Task.CompletedTask will be a bit faster
 250:              return Task.FromResult(0);
 251:          }
 252:          #endregion
 253:   
 254:          #region snippet_SetCookies
 255:          private Task SetCookies(object context)
 256:          {
 257:              var httpContext = (HttpContext)context;
 258:   
 259:              IResponseCookies responseCookies = httpContext.Response.Cookies;
 260:   
 261:              responseCookies.Append("cookie1name", "cookie1value");
 262:              responseCookies.Append("cookie2name", "cookie2value",
 263:                  new CookieOptions { Expires = System.DateTime.Now.AddDays(5), HttpOnly = true });
 264:   
 265:              // If you use .Net 4.6+, Task.CompletedTask will be a bit faster
 266:              return Task.FromResult(0); 
 267:          }
 268:          #endregion
 269:   
 270:          // You would normally use MVC to generate HTML like this.
 271:          private string GetResponseContent()
 272:          {
 273:              return @"
 274:  <!DOCTYPE html>
 275:  <html lang=""en"">
 276:  <head>
 277:      <title>index</title>
 278:  </head>
 279:  <body>
 280:  <form action=""form.context"" method=""post"">
 281:      <input type=""text"" name=""firstname"">
 282:      <input type=""text"" name=""lastname"">
 283:      <input type=""submit"" value=""Submit"">
 284:  </form> 
 285:  </body>
 286:  </html>
 287:  ";
 288:          }
 289:      }
 290:   
 291:      public static class HttpContextDemoMiddlewareExtensions
 292:      {
 293:          public static IApplicationBuilder UseHttpContextDemoMiddleware(this IApplicationBuilder builder)
 294:          {
 295:              return builder.UseMiddleware<HttpContextDemoMiddleware>();
 296:          }
 297:      }
 298:  }

HttpContext.Request.UserHostAddress translates to:

[!code-csharpMain]

   1:  using Microsoft.AspNetCore.Builder;
   2:  using Microsoft.AspNetCore.Http;
   3:  using System.Collections.Generic;
   4:  using System.Threading.Tasks;
   5:  using Microsoft.Net.Http.Headers;
   6:  using Microsoft.AspNetCore.Http.Extensions;
   7:  using Microsoft.AspNetCore.Routing;
   8:   
   9:  namespace MyApp.Middleware
  10:  {
  11:      public class HttpContextDemoMiddleware
  12:      {
  13:          private readonly RequestDelegate _next;
  14:   
  15:          public HttpContextDemoMiddleware(RequestDelegate next)
  16:          {
  17:              _next = next;
  18:          }
  19:   
  20:          public async Task Invoke(HttpContext httpContext)
  21:          {
  22:              // OnStarting handlers have to be set early during request processing,
  23:              // even though they are used to create the response.
  24:   
  25:              // ----------------------
  26:              // ASP.NET 4 - HttpContext.Response.Headers  
  27:              // ASP.NET 4 - HttpContext.Response.Cookies  
  28:              // 
  29:              // Issue with all response headers is that they will not be sent 
  30:              // after anything has been written to the response body.
  31:              // To solve this, use OnStarting to set a callback that will be called 
  32:              // right before headers are sent. Set the headers in that callback.
  33:              //
  34:              // Setting a cookie results in a Set-Cookie response header.
  35:              // So use an OnStarting handler here as well.
  36:   
  37:              //>40
  38:              httpContext.Response.OnStarting(SetHeaders, state: httpContext);
  39:              httpContext.Response.OnStarting(SetCookies, state: httpContext);
  40:              //<40
  41:   
  42:              // ==================================================================
  43:              // Context
  44:   
  45:              // Unique request ID (no ASP.NET 4 counterpart)
  46:              #region snippet_Trace
  47:              string requestId = httpContext.TraceIdentifier;
  48:              #endregion
  49:   
  50:              // ASP.NET 4 - HttpContext.Items
  51:              #region snippet_Items
  52:              IDictionary<object, object> items = httpContext.Items;
  53:              #endregion
  54:   
  55:              // ==================================================================
  56:              // Request
  57:   
  58:              // ASP.NET 4 - HttpContext.Request.HttpMethod
  59:              #region snippet_Method
  60:              string httpMethod = httpContext.Request.Method;
  61:              #endregion
  62:   
  63:              // ----------
  64:   
  65:              // ASP.NET 4 - HttpContext.Request.QueryString
  66:              #region snippet_Query
  67:              IQueryCollection queryParameters = httpContext.Request.Query;
  68:   
  69:              // If no query parameter "key" used, values will have 0 items
  70:              // If single value used for a key (...?key=v1), values will have 1 item ("v1")
  71:              // If key has multiple values (...?key=v1&key=v2), values will have 2 items ("v1" and "v2")
  72:              IList<string> values = queryParameters["key"];
  73:   
  74:              // If no query parameter "key" used, value will be ""
  75:              // If single value used for a key (...?key=v1), value will be "v1"
  76:              // If key has multiple values (...?key=v1&key=v2), value will be "v1,v2"
  77:              string value = queryParameters["key"].ToString();
  78:              #endregion
  79:   
  80:              // ASP.NET 4 - HttpContext.Request.Url and HttpContext.Request.RawUrl
  81:              #region snippet_Url
  82:              // using Microsoft.AspNetCore.Http.Extensions;
  83:              var url = httpContext.Request.GetDisplayUrl();
  84:              #endregion
  85:   
  86:              // ASP.NET 4 - HttpContext.Request.IsSecureConnection
  87:              #region snippet_Secure
  88:              var isSecureConnection = httpContext.Request.IsHttps;
  89:              #endregion
  90:   
  91:              // ASP.NET 4 - HttpContext.Request.UserHostAddress
  92:              #region snippet_Host
  93:              var userHostAddress = httpContext.Connection.RemoteIpAddress?.ToString();
  94:              #endregion
  95:   
  96:              // ASP.NET 4 - HttpContext.Request.Cookies 
  97:              #region snippet_Cookies
  98:              IRequestCookieCollection cookies = httpContext.Request.Cookies;
  99:              string unknownCookieValue = cookies["unknownCookie"]; // will be null (no exception)
 100:              string knownCookieValue = cookies["cookie1name"];     // will be actual value
 101:              #endregion
 102:   
 103:              // ASP.NET 4 - HttpContext.Request.RequestContext.RouteData
 104:              // using Microsoft.AspNetCore.Routing;
 105:              #region snippet_Route
 106:              var routeValue = httpContext.GetRouteValue("key");
 107:              #endregion
 108:   
 109:              // ASP.NET 4 - HttpContext.Request.Headers
 110:              #region snippet_Headers
 111:              // using Microsoft.AspNetCore.Http.Headers;
 112:              // using Microsoft.Net.Http.Headers;
 113:   
 114:              IHeaderDictionary headersDictionary = httpContext.Request.Headers;
 115:   
 116:              // GetTypedHeaders extension method provides strongly typed access to many headers
 117:              var requestHeaders = httpContext.Request.GetTypedHeaders();
 118:              CacheControlHeaderValue cacheControlHeaderValue = requestHeaders.CacheControl;
 119:   
 120:              // For unknown header, unknownheaderValues has zero items and unknownheaderValue is ""
 121:              IList<string> unknownheaderValues = headersDictionary["unknownheader"];
 122:              string unknownheaderValue = headersDictionary["unknownheader"].ToString();
 123:   
 124:              // For known header, knownheaderValues has 1 item and knownheaderValue is the value
 125:              IList<string> knownheaderValues = headersDictionary[HeaderNames.AcceptLanguage];
 126:              string knownheaderValue = headersDictionary[HeaderNames.AcceptLanguage].ToString();
 127:              #endregion
 128:   
 129:              // ASP.NET 4 - HttpContext.Request.UserAgent
 130:              #region snippet_Agent
 131:              string userAgent = headersDictionary[HeaderNames.UserAgent].ToString();
 132:              #endregion
 133:   
 134:              // ASP.NET 4 - HttpContext.Request.UrlReferrer
 135:              #region snippet_Referrer
 136:              string urlReferrer = headersDictionary[HeaderNames.Referer].ToString();
 137:              #endregion
 138:   
 139:              // ASP.NET 4 - HttpContext.Request.ContentType 
 140:              #region snippet_Type
 141:              // using Microsoft.Net.Http.Headers;
 142:   
 143:              MediaTypeHeaderValue mediaHeaderValue = requestHeaders.ContentType;
 144:              string contentType = mediaHeaderValue?.MediaType;   // ex. application/x-www-form-urlencoded
 145:              string contentMainType = mediaHeaderValue?.Type;    // ex. application
 146:              string contentSubType = mediaHeaderValue?.SubType;  // ex. x-www-form-urlencoded
 147:   
 148:              System.Text.Encoding requestEncoding = mediaHeaderValue?.Encoding;
 149:              #endregion
 150:   
 151:              // ASP.NET 4 - HttpContext.Request.Form 
 152:              #region snippet_Form
 153:              if (httpContext.Request.HasFormContentType)
 154:              {
 155:                  IFormCollection form;
 156:   
 157:                  form = httpContext.Request.Form; // sync
 158:                  // Or
 159:                  form = await httpContext.Request.ReadFormAsync(); // async
 160:   
 161:                  string firstName = form["firstname"];
 162:                  string lastName = form["lastname"];
 163:              }
 164:              #endregion
 165:   
 166:              // ----------
 167:              // See 
 168:              // http://stackoverflow.com/questions/31389781/read-body-twice-in-asp-net-5/
 169:   
 170:              // ASP.NET 4 - HttpContext.Request.InputStream
 171:              // Unlike reading the form, reading the raw body is not from a buffer.
 172:              // So you can only do this once per request.
 173:              // 
 174:              // If you need to read the body multiple times per request, see
 175:              // http://stackoverflow.com/questions/31389781/read-body-twice-in-asp-net-5/
 176:   
 177:              #region snippet_Input
 178:              string inputBody;
 179:              using (var reader = new System.IO.StreamReader(
 180:                  httpContext.Request.Body, System.Text.Encoding.UTF8))
 181:              {
 182:                  inputBody = reader.ReadToEnd();
 183:              }
 184:              #endregion
 185:   
 186:              // Use this middleware as a handler, so no call to 
 187:              // await _next.Invoke(aspnetCoreHttpContext);
 188:   
 189:              // ==================================================================
 190:              // Response
 191:   
 192:              // ASP.NET 4 - HttpContext.Response.Status  
 193:              // ASP.NET 4 - HttpContext.Response.StatusDescription (obsolete, removed from HTTP/2) 
 194:              #region snippet_Status
 195:              // using Microsoft.AspNetCore.Http;
 196:              httpContext.Response.StatusCode = StatusCodes.Status200OK;
 197:              #endregion
 198:   
 199:              // ASP.NET 4 - HttpContext.Response.ContentEncoding and HttpContext.Response.ContentType  
 200:              #region snippet_RespType
 201:              // using Microsoft.Net.Http.Headers;
 202:              var mediaType = new MediaTypeHeaderValue("application/json");
 203:              mediaType.Encoding = System.Text.Encoding.UTF8;
 204:              httpContext.Response.ContentType = mediaType.ToString();
 205:              #endregion
 206:   
 207:              // ASP.NET 4 - HttpContext.Response.ContentType only 
 208:              #region snippet_RespTypeOnly
 209:              httpContext.Response.ContentType = "text/html";
 210:              #endregion
 211:   
 212:              // ASP.NET 4 - HttpContext.Response.Output  
 213:              #region  snippet_Output
 214:              string responseContent = GetResponseContent();
 215:              await httpContext.Response.WriteAsync(responseContent);
 216:              #endregion
 217:          }
 218:   
 219:          #region snippet_SetHeaders
 220:          // using Microsoft.AspNet.Http.Headers;
 221:          // using Microsoft.Net.Http.Headers;
 222:   
 223:          private Task SetHeaders(object context)
 224:          {
 225:              var httpContext = (HttpContext)context;
 226:   
 227:              // Set header with single value
 228:              httpContext.Response.Headers["ResponseHeaderName"] = "headerValue";
 229:   
 230:              // Set header with multiple values
 231:              string[] responseHeaderValues = new string[] { "headerValue1", "headerValue1" };
 232:              httpContext.Response.Headers["ResponseHeaderName"] = responseHeaderValues;
 233:   
 234:              // Translating ASP.NET 4's HttpContext.Response.RedirectLocation  
 235:              httpContext.Response.Headers[HeaderNames.Location] = "http://www.example.com";
 236:              // Or
 237:              httpContext.Response.Redirect("http://www.example.com");
 238:   
 239:              // GetTypedHeaders extension method provides strongly typed access to many headers
 240:              var responseHeaders = httpContext.Response.GetTypedHeaders();
 241:   
 242:              // Translating ASP.NET 4's HttpContext.Response.CacheControl 
 243:              responseHeaders.CacheControl = new CacheControlHeaderValue
 244:              {
 245:                  MaxAge = new System.TimeSpan(365, 0, 0, 0)
 246:                  // Many more properties available 
 247:              };
 248:   
 249:              // If you use .Net 4.6+, Task.CompletedTask will be a bit faster
 250:              return Task.FromResult(0);
 251:          }
 252:          #endregion
 253:   
 254:          #region snippet_SetCookies
 255:          private Task SetCookies(object context)
 256:          {
 257:              var httpContext = (HttpContext)context;
 258:   
 259:              IResponseCookies responseCookies = httpContext.Response.Cookies;
 260:   
 261:              responseCookies.Append("cookie1name", "cookie1value");
 262:              responseCookies.Append("cookie2name", "cookie2value",
 263:                  new CookieOptions { Expires = System.DateTime.Now.AddDays(5), HttpOnly = true });
 264:   
 265:              // If you use .Net 4.6+, Task.CompletedTask will be a bit faster
 266:              return Task.FromResult(0); 
 267:          }
 268:          #endregion
 269:   
 270:          // You would normally use MVC to generate HTML like this.
 271:          private string GetResponseContent()
 272:          {
 273:              return @"
 274:  <!DOCTYPE html>
 275:  <html lang=""en"">
 276:  <head>
 277:      <title>index</title>
 278:  </head>
 279:  <body>
 280:  <form action=""form.context"" method=""post"">
 281:      <input type=""text"" name=""firstname"">
 282:      <input type=""text"" name=""lastname"">
 283:      <input type=""submit"" value=""Submit"">
 284:  </form> 
 285:  </body>
 286:  </html>
 287:  ";
 288:          }
 289:      }
 290:   
 291:      public static class HttpContextDemoMiddlewareExtensions
 292:      {
 293:          public static IApplicationBuilder UseHttpContextDemoMiddleware(this IApplicationBuilder builder)
 294:          {
 295:              return builder.UseMiddleware<HttpContextDemoMiddleware>();
 296:          }
 297:      }
 298:  }

HttpContext.Request.Cookies translates to:

[!code-csharpMain]

   1:  using Microsoft.AspNetCore.Builder;
   2:  using Microsoft.AspNetCore.Http;
   3:  using System.Collections.Generic;
   4:  using System.Threading.Tasks;
   5:  using Microsoft.Net.Http.Headers;
   6:  using Microsoft.AspNetCore.Http.Extensions;
   7:  using Microsoft.AspNetCore.Routing;
   8:   
   9:  namespace MyApp.Middleware
  10:  {
  11:      public class HttpContextDemoMiddleware
  12:      {
  13:          private readonly RequestDelegate _next;
  14:   
  15:          public HttpContextDemoMiddleware(RequestDelegate next)
  16:          {
  17:              _next = next;
  18:          }
  19:   
  20:          public async Task Invoke(HttpContext httpContext)
  21:          {
  22:              // OnStarting handlers have to be set early during request processing,
  23:              // even though they are used to create the response.
  24:   
  25:              // ----------------------
  26:              // ASP.NET 4 - HttpContext.Response.Headers  
  27:              // ASP.NET 4 - HttpContext.Response.Cookies  
  28:              // 
  29:              // Issue with all response headers is that they will not be sent 
  30:              // after anything has been written to the response body.
  31:              // To solve this, use OnStarting to set a callback that will be called 
  32:              // right before headers are sent. Set the headers in that callback.
  33:              //
  34:              // Setting a cookie results in a Set-Cookie response header.
  35:              // So use an OnStarting handler here as well.
  36:   
  37:              //>40
  38:              httpContext.Response.OnStarting(SetHeaders, state: httpContext);
  39:              httpContext.Response.OnStarting(SetCookies, state: httpContext);
  40:              //<40
  41:   
  42:              // ==================================================================
  43:              // Context
  44:   
  45:              // Unique request ID (no ASP.NET 4 counterpart)
  46:              #region snippet_Trace
  47:              string requestId = httpContext.TraceIdentifier;
  48:              #endregion
  49:   
  50:              // ASP.NET 4 - HttpContext.Items
  51:              #region snippet_Items
  52:              IDictionary<object, object> items = httpContext.Items;
  53:              #endregion
  54:   
  55:              // ==================================================================
  56:              // Request
  57:   
  58:              // ASP.NET 4 - HttpContext.Request.HttpMethod
  59:              #region snippet_Method
  60:              string httpMethod = httpContext.Request.Method;
  61:              #endregion
  62:   
  63:              // ----------
  64:   
  65:              // ASP.NET 4 - HttpContext.Request.QueryString
  66:              #region snippet_Query
  67:              IQueryCollection queryParameters = httpContext.Request.Query;
  68:   
  69:              // If no query parameter "key" used, values will have 0 items
  70:              // If single value used for a key (...?key=v1), values will have 1 item ("v1")
  71:              // If key has multiple values (...?key=v1&key=v2), values will have 2 items ("v1" and "v2")
  72:              IList<string> values = queryParameters["key"];
  73:   
  74:              // If no query parameter "key" used, value will be ""
  75:              // If single value used for a key (...?key=v1), value will be "v1"
  76:              // If key has multiple values (...?key=v1&key=v2), value will be "v1,v2"
  77:              string value = queryParameters["key"].ToString();
  78:              #endregion
  79:   
  80:              // ASP.NET 4 - HttpContext.Request.Url and HttpContext.Request.RawUrl
  81:              #region snippet_Url
  82:              // using Microsoft.AspNetCore.Http.Extensions;
  83:              var url = httpContext.Request.GetDisplayUrl();
  84:              #endregion
  85:   
  86:              // ASP.NET 4 - HttpContext.Request.IsSecureConnection
  87:              #region snippet_Secure
  88:              var isSecureConnection = httpContext.Request.IsHttps;
  89:              #endregion
  90:   
  91:              // ASP.NET 4 - HttpContext.Request.UserHostAddress
  92:              #region snippet_Host
  93:              var userHostAddress = httpContext.Connection.RemoteIpAddress?.ToString();
  94:              #endregion
  95:   
  96:              // ASP.NET 4 - HttpContext.Request.Cookies 
  97:              #region snippet_Cookies
  98:              IRequestCookieCollection cookies = httpContext.Request.Cookies;
  99:              string unknownCookieValue = cookies["unknownCookie"]; // will be null (no exception)
 100:              string knownCookieValue = cookies["cookie1name"];     // will be actual value
 101:              #endregion
 102:   
 103:              // ASP.NET 4 - HttpContext.Request.RequestContext.RouteData
 104:              // using Microsoft.AspNetCore.Routing;
 105:              #region snippet_Route
 106:              var routeValue = httpContext.GetRouteValue("key");
 107:              #endregion
 108:   
 109:              // ASP.NET 4 - HttpContext.Request.Headers
 110:              #region snippet_Headers
 111:              // using Microsoft.AspNetCore.Http.Headers;
 112:              // using Microsoft.Net.Http.Headers;
 113:   
 114:              IHeaderDictionary headersDictionary = httpContext.Request.Headers;
 115:   
 116:              // GetTypedHeaders extension method provides strongly typed access to many headers
 117:              var requestHeaders = httpContext.Request.GetTypedHeaders();
 118:              CacheControlHeaderValue cacheControlHeaderValue = requestHeaders.CacheControl;
 119:   
 120:              // For unknown header, unknownheaderValues has zero items and unknownheaderValue is ""
 121:              IList<string> unknownheaderValues = headersDictionary["unknownheader"];
 122:              string unknownheaderValue = headersDictionary["unknownheader"].ToString();
 123:   
 124:              // For known header, knownheaderValues has 1 item and knownheaderValue is the value
 125:              IList<string> knownheaderValues = headersDictionary[HeaderNames.AcceptLanguage];
 126:              string knownheaderValue = headersDictionary[HeaderNames.AcceptLanguage].ToString();
 127:              #endregion
 128:   
 129:              // ASP.NET 4 - HttpContext.Request.UserAgent
 130:              #region snippet_Agent
 131:              string userAgent = headersDictionary[HeaderNames.UserAgent].ToString();
 132:              #endregion
 133:   
 134:              // ASP.NET 4 - HttpContext.Request.UrlReferrer
 135:              #region snippet_Referrer
 136:              string urlReferrer = headersDictionary[HeaderNames.Referer].ToString();
 137:              #endregion
 138:   
 139:              // ASP.NET 4 - HttpContext.Request.ContentType 
 140:              #region snippet_Type
 141:              // using Microsoft.Net.Http.Headers;
 142:   
 143:              MediaTypeHeaderValue mediaHeaderValue = requestHeaders.ContentType;
 144:              string contentType = mediaHeaderValue?.MediaType;   // ex. application/x-www-form-urlencoded
 145:              string contentMainType = mediaHeaderValue?.Type;    // ex. application
 146:              string contentSubType = mediaHeaderValue?.SubType;  // ex. x-www-form-urlencoded
 147:   
 148:              System.Text.Encoding requestEncoding = mediaHeaderValue?.Encoding;
 149:              #endregion
 150:   
 151:              // ASP.NET 4 - HttpContext.Request.Form 
 152:              #region snippet_Form
 153:              if (httpContext.Request.HasFormContentType)
 154:              {
 155:                  IFormCollection form;
 156:   
 157:                  form = httpContext.Request.Form; // sync
 158:                  // Or
 159:                  form = await httpContext.Request.ReadFormAsync(); // async
 160:   
 161:                  string firstName = form["firstname"];
 162:                  string lastName = form["lastname"];
 163:              }
 164:              #endregion
 165:   
 166:              // ----------
 167:              // See 
 168:              // http://stackoverflow.com/questions/31389781/read-body-twice-in-asp-net-5/
 169:   
 170:              // ASP.NET 4 - HttpContext.Request.InputStream
 171:              // Unlike reading the form, reading the raw body is not from a buffer.
 172:              // So you can only do this once per request.
 173:              // 
 174:              // If you need to read the body multiple times per request, see
 175:              // http://stackoverflow.com/questions/31389781/read-body-twice-in-asp-net-5/
 176:   
 177:              #region snippet_Input
 178:              string inputBody;
 179:              using (var reader = new System.IO.StreamReader(
 180:                  httpContext.Request.Body, System.Text.Encoding.UTF8))
 181:              {
 182:                  inputBody = reader.ReadToEnd();
 183:              }
 184:              #endregion
 185:   
 186:              // Use this middleware as a handler, so no call to 
 187:              // await _next.Invoke(aspnetCoreHttpContext);
 188:   
 189:              // ==================================================================
 190:              // Response
 191:   
 192:              // ASP.NET 4 - HttpContext.Response.Status  
 193:              // ASP.NET 4 - HttpContext.Response.StatusDescription (obsolete, removed from HTTP/2) 
 194:              #region snippet_Status
 195:              // using Microsoft.AspNetCore.Http;
 196:              httpContext.Response.StatusCode = StatusCodes.Status200OK;
 197:              #endregion
 198:   
 199:              // ASP.NET 4 - HttpContext.Response.ContentEncoding and HttpContext.Response.ContentType  
 200:              #region snippet_RespType
 201:              // using Microsoft.Net.Http.Headers;
 202:              var mediaType = new MediaTypeHeaderValue("application/json");
 203:              mediaType.Encoding = System.Text.Encoding.UTF8;
 204:              httpContext.Response.ContentType = mediaType.ToString();
 205:              #endregion
 206:   
 207:              // ASP.NET 4 - HttpContext.Response.ContentType only 
 208:              #region snippet_RespTypeOnly
 209:              httpContext.Response.ContentType = "text/html";
 210:              #endregion
 211:   
 212:              // ASP.NET 4 - HttpContext.Response.Output  
 213:              #region  snippet_Output
 214:              string responseContent = GetResponseContent();
 215:              await httpContext.Response.WriteAsync(responseContent);
 216:              #endregion
 217:          }
 218:   
 219:          #region snippet_SetHeaders
 220:          // using Microsoft.AspNet.Http.Headers;
 221:          // using Microsoft.Net.Http.Headers;
 222:   
 223:          private Task SetHeaders(object context)
 224:          {
 225:              var httpContext = (HttpContext)context;
 226:   
 227:              // Set header with single value
 228:              httpContext.Response.Headers["ResponseHeaderName"] = "headerValue";
 229:   
 230:              // Set header with multiple values
 231:              string[] responseHeaderValues = new string[] { "headerValue1", "headerValue1" };
 232:              httpContext.Response.Headers["ResponseHeaderName"] = responseHeaderValues;
 233:   
 234:              // Translating ASP.NET 4's HttpContext.Response.RedirectLocation  
 235:              httpContext.Response.Headers[HeaderNames.Location] = "http://www.example.com";
 236:              // Or
 237:              httpContext.Response.Redirect("http://www.example.com");
 238:   
 239:              // GetTypedHeaders extension method provides strongly typed access to many headers
 240:              var responseHeaders = httpContext.Response.GetTypedHeaders();
 241:   
 242:              // Translating ASP.NET 4's HttpContext.Response.CacheControl 
 243:              responseHeaders.CacheControl = new CacheControlHeaderValue
 244:              {
 245:                  MaxAge = new System.TimeSpan(365, 0, 0, 0)
 246:                  // Many more properties available 
 247:              };
 248:   
 249:              // If you use .Net 4.6+, Task.CompletedTask will be a bit faster
 250:              return Task.FromResult(0);
 251:          }
 252:          #endregion
 253:   
 254:          #region snippet_SetCookies
 255:          private Task SetCookies(object context)
 256:          {
 257:              var httpContext = (HttpContext)context;
 258:   
 259:              IResponseCookies responseCookies = httpContext.Response.Cookies;
 260:   
 261:              responseCookies.Append("cookie1name", "cookie1value");
 262:              responseCookies.Append("cookie2name", "cookie2value",
 263:                  new CookieOptions { Expires = System.DateTime.Now.AddDays(5), HttpOnly = true });
 264:   
 265:              // If you use .Net 4.6+, Task.CompletedTask will be a bit faster
 266:              return Task.FromResult(0); 
 267:          }
 268:          #endregion
 269:   
 270:          // You would normally use MVC to generate HTML like this.
 271:          private string GetResponseContent()
 272:          {
 273:              return @"
 274:  <!DOCTYPE html>
 275:  <html lang=""en"">
 276:  <head>
 277:      <title>index</title>
 278:  </head>
 279:  <body>
 280:  <form action=""form.context"" method=""post"">
 281:      <input type=""text"" name=""firstname"">
 282:      <input type=""text"" name=""lastname"">
 283:      <input type=""submit"" value=""Submit"">
 284:  </form> 
 285:  </body>
 286:  </html>
 287:  ";
 288:          }
 289:      }
 290:   
 291:      public static class HttpContextDemoMiddlewareExtensions
 292:      {
 293:          public static IApplicationBuilder UseHttpContextDemoMiddleware(this IApplicationBuilder builder)
 294:          {
 295:              return builder.UseMiddleware<HttpContextDemoMiddleware>();
 296:          }
 297:      }
 298:  }

HttpContext.Request.RequestContext.RouteData translates to:

[!code-csharpMain]

   1:  using Microsoft.AspNetCore.Builder;
   2:  using Microsoft.AspNetCore.Http;
   3:  using System.Collections.Generic;
   4:  using System.Threading.Tasks;
   5:  using Microsoft.Net.Http.Headers;
   6:  using Microsoft.AspNetCore.Http.Extensions;
   7:  using Microsoft.AspNetCore.Routing;
   8:   
   9:  namespace MyApp.Middleware
  10:  {
  11:      public class HttpContextDemoMiddleware
  12:      {
  13:          private readonly RequestDelegate _next;
  14:   
  15:          public HttpContextDemoMiddleware(RequestDelegate next)
  16:          {
  17:              _next = next;
  18:          }
  19:   
  20:          public async Task Invoke(HttpContext httpContext)
  21:          {
  22:              // OnStarting handlers have to be set early during request processing,
  23:              // even though they are used to create the response.
  24:   
  25:              // ----------------------
  26:              // ASP.NET 4 - HttpContext.Response.Headers  
  27:              // ASP.NET 4 - HttpContext.Response.Cookies  
  28:              // 
  29:              // Issue with all response headers is that they will not be sent 
  30:              // after anything has been written to the response body.
  31:              // To solve this, use OnStarting to set a callback that will be called 
  32:              // right before headers are sent. Set the headers in that callback.
  33:              //
  34:              // Setting a cookie results in a Set-Cookie response header.
  35:              // So use an OnStarting handler here as well.
  36:   
  37:              //>40
  38:              httpContext.Response.OnStarting(SetHeaders, state: httpContext);
  39:              httpContext.Response.OnStarting(SetCookies, state: httpContext);
  40:              //<40
  41:   
  42:              // ==================================================================
  43:              // Context
  44:   
  45:              // Unique request ID (no ASP.NET 4 counterpart)
  46:              #region snippet_Trace
  47:              string requestId = httpContext.TraceIdentifier;
  48:              #endregion
  49:   
  50:              // ASP.NET 4 - HttpContext.Items
  51:              #region snippet_Items
  52:              IDictionary<object, object> items = httpContext.Items;
  53:              #endregion
  54:   
  55:              // ==================================================================
  56:              // Request
  57:   
  58:              // ASP.NET 4 - HttpContext.Request.HttpMethod
  59:              #region snippet_Method
  60:              string httpMethod = httpContext.Request.Method;
  61:              #endregion
  62:   
  63:              // ----------
  64:   
  65:              // ASP.NET 4 - HttpContext.Request.QueryString
  66:              #region snippet_Query
  67:              IQueryCollection queryParameters = httpContext.Request.Query;
  68:   
  69:              // If no query parameter "key" used, values will have 0 items
  70:              // If single value used for a key (...?key=v1), values will have 1 item ("v1")
  71:              // If key has multiple values (...?key=v1&key=v2), values will have 2 items ("v1" and "v2")
  72:              IList<string> values = queryParameters["key"];
  73:   
  74:              // If no query parameter "key" used, value will be ""
  75:              // If single value used for a key (...?key=v1), value will be "v1"
  76:              // If key has multiple values (...?key=v1&key=v2), value will be "v1,v2"
  77:              string value = queryParameters["key"].ToString();
  78:              #endregion
  79:   
  80:              // ASP.NET 4 - HttpContext.Request.Url and HttpContext.Request.RawUrl
  81:              #region snippet_Url
  82:              // using Microsoft.AspNetCore.Http.Extensions;
  83:              var url = httpContext.Request.GetDisplayUrl();
  84:              #endregion
  85:   
  86:              // ASP.NET 4 - HttpContext.Request.IsSecureConnection
  87:              #region snippet_Secure
  88:              var isSecureConnection = httpContext.Request.IsHttps;
  89:              #endregion
  90:   
  91:              // ASP.NET 4 - HttpContext.Request.UserHostAddress
  92:              #region snippet_Host
  93:              var userHostAddress = httpContext.Connection.RemoteIpAddress?.ToString();
  94:              #endregion
  95:   
  96:              // ASP.NET 4 - HttpContext.Request.Cookies 
  97:              #region snippet_Cookies
  98:              IRequestCookieCollection cookies = httpContext.Request.Cookies;
  99:              string unknownCookieValue = cookies["unknownCookie"]; // will be null (no exception)
 100:              string knownCookieValue = cookies["cookie1name"];     // will be actual value
 101:              #endregion
 102:   
 103:              // ASP.NET 4 - HttpContext.Request.RequestContext.RouteData
 104:              // using Microsoft.AspNetCore.Routing;
 105:              #region snippet_Route
 106:              var routeValue = httpContext.GetRouteValue("key");
 107:              #endregion
 108:   
 109:              // ASP.NET 4 - HttpContext.Request.Headers
 110:              #region snippet_Headers
 111:              // using Microsoft.AspNetCore.Http.Headers;
 112:              // using Microsoft.Net.Http.Headers;
 113:   
 114:              IHeaderDictionary headersDictionary = httpContext.Request.Headers;
 115:   
 116:              // GetTypedHeaders extension method provides strongly typed access to many headers
 117:              var requestHeaders = httpContext.Request.GetTypedHeaders();
 118:              CacheControlHeaderValue cacheControlHeaderValue = requestHeaders.CacheControl;
 119:   
 120:              // For unknown header, unknownheaderValues has zero items and unknownheaderValue is ""
 121:              IList<string> unknownheaderValues = headersDictionary["unknownheader"];
 122:              string unknownheaderValue = headersDictionary["unknownheader"].ToString();
 123:   
 124:              // For known header, knownheaderValues has 1 item and knownheaderValue is the value
 125:              IList<string> knownheaderValues = headersDictionary[HeaderNames.AcceptLanguage];
 126:              string knownheaderValue = headersDictionary[HeaderNames.AcceptLanguage].ToString();
 127:              #endregion
 128:   
 129:              // ASP.NET 4 - HttpContext.Request.UserAgent
 130:              #region snippet_Agent
 131:              string userAgent = headersDictionary[HeaderNames.UserAgent].ToString();
 132:              #endregion
 133:   
 134:              // ASP.NET 4 - HttpContext.Request.UrlReferrer
 135:              #region snippet_Referrer
 136:              string urlReferrer = headersDictionary[HeaderNames.Referer].ToString();
 137:              #endregion
 138:   
 139:              // ASP.NET 4 - HttpContext.Request.ContentType 
 140:              #region snippet_Type
 141:              // using Microsoft.Net.Http.Headers;
 142:   
 143:              MediaTypeHeaderValue mediaHeaderValue = requestHeaders.ContentType;
 144:              string contentType = mediaHeaderValue?.MediaType;   // ex. application/x-www-form-urlencoded
 145:              string contentMainType = mediaHeaderValue?.Type;    // ex. application
 146:              string contentSubType = mediaHeaderValue?.SubType;  // ex. x-www-form-urlencoded
 147:   
 148:              System.Text.Encoding requestEncoding = mediaHeaderValue?.Encoding;
 149:              #endregion
 150:   
 151:              // ASP.NET 4 - HttpContext.Request.Form 
 152:              #region snippet_Form
 153:              if (httpContext.Request.HasFormContentType)
 154:              {
 155:                  IFormCollection form;
 156:   
 157:                  form = httpContext.Request.Form; // sync
 158:                  // Or
 159:                  form = await httpContext.Request.ReadFormAsync(); // async
 160:   
 161:                  string firstName = form["firstname"];
 162:                  string lastName = form["lastname"];
 163:              }
 164:              #endregion
 165:   
 166:              // ----------
 167:              // See 
 168:              // http://stackoverflow.com/questions/31389781/read-body-twice-in-asp-net-5/
 169:   
 170:              // ASP.NET 4 - HttpContext.Request.InputStream
 171:              // Unlike reading the form, reading the raw body is not from a buffer.
 172:              // So you can only do this once per request.
 173:              // 
 174:              // If you need to read the body multiple times per request, see
 175:              // http://stackoverflow.com/questions/31389781/read-body-twice-in-asp-net-5/
 176:   
 177:              #region snippet_Input
 178:              string inputBody;
 179:              using (var reader = new System.IO.StreamReader(
 180:                  httpContext.Request.Body, System.Text.Encoding.UTF8))
 181:              {
 182:                  inputBody = reader.ReadToEnd();
 183:              }
 184:              #endregion
 185:   
 186:              // Use this middleware as a handler, so no call to 
 187:              // await _next.Invoke(aspnetCoreHttpContext);
 188:   
 189:              // ==================================================================
 190:              // Response
 191:   
 192:              // ASP.NET 4 - HttpContext.Response.Status  
 193:              // ASP.NET 4 - HttpContext.Response.StatusDescription (obsolete, removed from HTTP/2) 
 194:              #region snippet_Status
 195:              // using Microsoft.AspNetCore.Http;
 196:              httpContext.Response.StatusCode = StatusCodes.Status200OK;
 197:              #endregion
 198:   
 199:              // ASP.NET 4 - HttpContext.Response.ContentEncoding and HttpContext.Response.ContentType  
 200:              #region snippet_RespType
 201:              // using Microsoft.Net.Http.Headers;
 202:              var mediaType = new MediaTypeHeaderValue("application/json");
 203:              mediaType.Encoding = System.Text.Encoding.UTF8;
 204:              httpContext.Response.ContentType = mediaType.ToString();
 205:              #endregion
 206:   
 207:              // ASP.NET 4 - HttpContext.Response.ContentType only 
 208:              #region snippet_RespTypeOnly
 209:              httpContext.Response.ContentType = "text/html";
 210:              #endregion
 211:   
 212:              // ASP.NET 4 - HttpContext.Response.Output  
 213:              #region  snippet_Output
 214:              string responseContent = GetResponseContent();
 215:              await httpContext.Response.WriteAsync(responseContent);
 216:              #endregion
 217:          }
 218:   
 219:          #region snippet_SetHeaders
 220:          // using Microsoft.AspNet.Http.Headers;
 221:          // using Microsoft.Net.Http.Headers;
 222:   
 223:          private Task SetHeaders(object context)
 224:          {
 225:              var httpContext = (HttpContext)context;
 226:   
 227:              // Set header with single value
 228:              httpContext.Response.Headers["ResponseHeaderName"] = "headerValue";
 229:   
 230:              // Set header with multiple values
 231:              string[] responseHeaderValues = new string[] { "headerValue1", "headerValue1" };
 232:              httpContext.Response.Headers["ResponseHeaderName"] = responseHeaderValues;
 233:   
 234:              // Translating ASP.NET 4's HttpContext.Response.RedirectLocation  
 235:              httpContext.Response.Headers[HeaderNames.Location] = "http://www.example.com";
 236:              // Or
 237:              httpContext.Response.Redirect("http://www.example.com");
 238:   
 239:              // GetTypedHeaders extension method provides strongly typed access to many headers
 240:              var responseHeaders = httpContext.Response.GetTypedHeaders();
 241:   
 242:              // Translating ASP.NET 4's HttpContext.Response.CacheControl 
 243:              responseHeaders.CacheControl = new CacheControlHeaderValue
 244:              {
 245:                  MaxAge = new System.TimeSpan(365, 0, 0, 0)
 246:                  // Many more properties available 
 247:              };
 248:   
 249:              // If you use .Net 4.6+, Task.CompletedTask will be a bit faster
 250:              return Task.FromResult(0);
 251:          }
 252:          #endregion
 253:   
 254:          #region snippet_SetCookies
 255:          private Task SetCookies(object context)
 256:          {
 257:              var httpContext = (HttpContext)context;
 258:   
 259:              IResponseCookies responseCookies = httpContext.Response.Cookies;
 260:   
 261:              responseCookies.Append("cookie1name", "cookie1value");
 262:              responseCookies.Append("cookie2name", "cookie2value",
 263:                  new CookieOptions { Expires = System.DateTime.Now.AddDays(5), HttpOnly = true });
 264:   
 265:              // If you use .Net 4.6+, Task.CompletedTask will be a bit faster
 266:              return Task.FromResult(0); 
 267:          }
 268:          #endregion
 269:   
 270:          // You would normally use MVC to generate HTML like this.
 271:          private string GetResponseContent()
 272:          {
 273:              return @"
 274:  <!DOCTYPE html>
 275:  <html lang=""en"">
 276:  <head>
 277:      <title>index</title>
 278:  </head>
 279:  <body>
 280:  <form action=""form.context"" method=""post"">
 281:      <input type=""text"" name=""firstname"">
 282:      <input type=""text"" name=""lastname"">
 283:      <input type=""submit"" value=""Submit"">
 284:  </form> 
 285:  </body>
 286:  </html>
 287:  ";
 288:          }
 289:      }
 290:   
 291:      public static class HttpContextDemoMiddlewareExtensions
 292:      {
 293:          public static IApplicationBuilder UseHttpContextDemoMiddleware(this IApplicationBuilder builder)
 294:          {
 295:              return builder.UseMiddleware<HttpContextDemoMiddleware>();
 296:          }
 297:      }
 298:  }

HttpContext.Request.Headers translates to:

[!code-csharpMain]

   1:  using Microsoft.AspNetCore.Builder;
   2:  using Microsoft.AspNetCore.Http;
   3:  using System.Collections.Generic;
   4:  using System.Threading.Tasks;
   5:  using Microsoft.Net.Http.Headers;
   6:  using Microsoft.AspNetCore.Http.Extensions;
   7:  using Microsoft.AspNetCore.Routing;
   8:   
   9:  namespace MyApp.Middleware
  10:  {
  11:      public class HttpContextDemoMiddleware
  12:      {
  13:          private readonly RequestDelegate _next;
  14:   
  15:          public HttpContextDemoMiddleware(RequestDelegate next)
  16:          {
  17:              _next = next;
  18:          }
  19:   
  20:          public async Task Invoke(HttpContext httpContext)
  21:          {
  22:              // OnStarting handlers have to be set early during request processing,
  23:              // even though they are used to create the response.
  24:   
  25:              // ----------------------
  26:              // ASP.NET 4 - HttpContext.Response.Headers  
  27:              // ASP.NET 4 - HttpContext.Response.Cookies  
  28:              // 
  29:              // Issue with all response headers is that they will not be sent 
  30:              // after anything has been written to the response body.
  31:              // To solve this, use OnStarting to set a callback that will be called 
  32:              // right before headers are sent. Set the headers in that callback.
  33:              //
  34:              // Setting a cookie results in a Set-Cookie response header.
  35:              // So use an OnStarting handler here as well.
  36:   
  37:              //>40
  38:              httpContext.Response.OnStarting(SetHeaders, state: httpContext);
  39:              httpContext.Response.OnStarting(SetCookies, state: httpContext);
  40:              //<40
  41:   
  42:              // ==================================================================
  43:              // Context
  44:   
  45:              // Unique request ID (no ASP.NET 4 counterpart)
  46:              #region snippet_Trace
  47:              string requestId = httpContext.TraceIdentifier;
  48:              #endregion
  49:   
  50:              // ASP.NET 4 - HttpContext.Items
  51:              #region snippet_Items
  52:              IDictionary<object, object> items = httpContext.Items;
  53:              #endregion
  54:   
  55:              // ==================================================================
  56:              // Request
  57:   
  58:              // ASP.NET 4 - HttpContext.Request.HttpMethod
  59:              #region snippet_Method
  60:              string httpMethod = httpContext.Request.Method;
  61:              #endregion
  62:   
  63:              // ----------
  64:   
  65:              // ASP.NET 4 - HttpContext.Request.QueryString
  66:              #region snippet_Query
  67:              IQueryCollection queryParameters = httpContext.Request.Query;
  68:   
  69:              // If no query parameter "key" used, values will have 0 items
  70:              // If single value used for a key (...?key=v1), values will have 1 item ("v1")
  71:              // If key has multiple values (...?key=v1&key=v2), values will have 2 items ("v1" and "v2")
  72:              IList<string> values = queryParameters["key"];
  73:   
  74:              // If no query parameter "key" used, value will be ""
  75:              // If single value used for a key (...?key=v1), value will be "v1"
  76:              // If key has multiple values (...?key=v1&key=v2), value will be "v1,v2"
  77:              string value = queryParameters["key"].ToString();
  78:              #endregion
  79:   
  80:              // ASP.NET 4 - HttpContext.Request.Url and HttpContext.Request.RawUrl
  81:              #region snippet_Url
  82:              // using Microsoft.AspNetCore.Http.Extensions;
  83:              var url = httpContext.Request.GetDisplayUrl();
  84:              #endregion
  85:   
  86:              // ASP.NET 4 - HttpContext.Request.IsSecureConnection
  87:              #region snippet_Secure
  88:              var isSecureConnection = httpContext.Request.IsHttps;
  89:              #endregion
  90:   
  91:              // ASP.NET 4 - HttpContext.Request.UserHostAddress
  92:              #region snippet_Host
  93:              var userHostAddress = httpContext.Connection.RemoteIpAddress?.ToString();
  94:              #endregion
  95:   
  96:              // ASP.NET 4 - HttpContext.Request.Cookies 
  97:              #region snippet_Cookies
  98:              IRequestCookieCollection cookies = httpContext.Request.Cookies;
  99:              string unknownCookieValue = cookies["unknownCookie"]; // will be null (no exception)
 100:              string knownCookieValue = cookies["cookie1name"];     // will be actual value
 101:              #endregion
 102:   
 103:              // ASP.NET 4 - HttpContext.Request.RequestContext.RouteData
 104:              // using Microsoft.AspNetCore.Routing;
 105:              #region snippet_Route
 106:              var routeValue = httpContext.GetRouteValue("key");
 107:              #endregion
 108:   
 109:              // ASP.NET 4 - HttpContext.Request.Headers
 110:              #region snippet_Headers
 111:              // using Microsoft.AspNetCore.Http.Headers;
 112:              // using Microsoft.Net.Http.Headers;
 113:   
 114:              IHeaderDictionary headersDictionary = httpContext.Request.Headers;
 115:   
 116:              // GetTypedHeaders extension method provides strongly typed access to many headers
 117:              var requestHeaders = httpContext.Request.GetTypedHeaders();
 118:              CacheControlHeaderValue cacheControlHeaderValue = requestHeaders.CacheControl;
 119:   
 120:              // For unknown header, unknownheaderValues has zero items and unknownheaderValue is ""
 121:              IList<string> unknownheaderValues = headersDictionary["unknownheader"];
 122:              string unknownheaderValue = headersDictionary["unknownheader"].ToString();
 123:   
 124:              // For known header, knownheaderValues has 1 item and knownheaderValue is the value
 125:              IList<string> knownheaderValues = headersDictionary[HeaderNames.AcceptLanguage];
 126:              string knownheaderValue = headersDictionary[HeaderNames.AcceptLanguage].ToString();
 127:              #endregion
 128:   
 129:              // ASP.NET 4 - HttpContext.Request.UserAgent
 130:              #region snippet_Agent
 131:              string userAgent = headersDictionary[HeaderNames.UserAgent].ToString();
 132:              #endregion
 133:   
 134:              // ASP.NET 4 - HttpContext.Request.UrlReferrer
 135:              #region snippet_Referrer
 136:              string urlReferrer = headersDictionary[HeaderNames.Referer].ToString();
 137:              #endregion
 138:   
 139:              // ASP.NET 4 - HttpContext.Request.ContentType 
 140:              #region snippet_Type
 141:              // using Microsoft.Net.Http.Headers;
 142:   
 143:              MediaTypeHeaderValue mediaHeaderValue = requestHeaders.ContentType;
 144:              string contentType = mediaHeaderValue?.MediaType;   // ex. application/x-www-form-urlencoded
 145:              string contentMainType = mediaHeaderValue?.Type;    // ex. application
 146:              string contentSubType = mediaHeaderValue?.SubType;  // ex. x-www-form-urlencoded
 147:   
 148:              System.Text.Encoding requestEncoding = mediaHeaderValue?.Encoding;
 149:              #endregion
 150:   
 151:              // ASP.NET 4 - HttpContext.Request.Form 
 152:              #region snippet_Form
 153:              if (httpContext.Request.HasFormContentType)
 154:              {
 155:                  IFormCollection form;
 156:   
 157:                  form = httpContext.Request.Form; // sync
 158:                  // Or
 159:                  form = await httpContext.Request.ReadFormAsync(); // async
 160:   
 161:                  string firstName = form["firstname"];
 162:                  string lastName = form["lastname"];
 163:              }
 164:              #endregion
 165:   
 166:              // ----------
 167:              // See 
 168:              // http://stackoverflow.com/questions/31389781/read-body-twice-in-asp-net-5/
 169:   
 170:              // ASP.NET 4 - HttpContext.Request.InputStream
 171:              // Unlike reading the form, reading the raw body is not from a buffer.
 172:              // So you can only do this once per request.
 173:              // 
 174:              // If you need to read the body multiple times per request, see
 175:              // http://stackoverflow.com/questions/31389781/read-body-twice-in-asp-net-5/
 176:   
 177:              #region snippet_Input
 178:              string inputBody;
 179:              using (var reader = new System.IO.StreamReader(
 180:                  httpContext.Request.Body, System.Text.Encoding.UTF8))
 181:              {
 182:                  inputBody = reader.ReadToEnd();
 183:              }
 184:              #endregion
 185:   
 186:              // Use this middleware as a handler, so no call to 
 187:              // await _next.Invoke(aspnetCoreHttpContext);
 188:   
 189:              // ==================================================================
 190:              // Response
 191:   
 192:              // ASP.NET 4 - HttpContext.Response.Status  
 193:              // ASP.NET 4 - HttpContext.Response.StatusDescription (obsolete, removed from HTTP/2) 
 194:              #region snippet_Status
 195:              // using Microsoft.AspNetCore.Http;
 196:              httpContext.Response.StatusCode = StatusCodes.Status200OK;
 197:              #endregion
 198:   
 199:              // ASP.NET 4 - HttpContext.Response.ContentEncoding and HttpContext.Response.ContentType  
 200:              #region snippet_RespType
 201:              // using Microsoft.Net.Http.Headers;
 202:              var mediaType = new MediaTypeHeaderValue("application/json");
 203:              mediaType.Encoding = System.Text.Encoding.UTF8;
 204:              httpContext.Response.ContentType = mediaType.ToString();
 205:              #endregion
 206:   
 207:              // ASP.NET 4 - HttpContext.Response.ContentType only 
 208:              #region snippet_RespTypeOnly
 209:              httpContext.Response.ContentType = "text/html";
 210:              #endregion
 211:   
 212:              // ASP.NET 4 - HttpContext.Response.Output  
 213:              #region  snippet_Output
 214:              string responseContent = GetResponseContent();
 215:              await httpContext.Response.WriteAsync(responseContent);
 216:              #endregion
 217:          }
 218:   
 219:          #region snippet_SetHeaders
 220:          // using Microsoft.AspNet.Http.Headers;
 221:          // using Microsoft.Net.Http.Headers;
 222:   
 223:          private Task SetHeaders(object context)
 224:          {
 225:              var httpContext = (HttpContext)context;
 226:   
 227:              // Set header with single value
 228:              httpContext.Response.Headers["ResponseHeaderName"] = "headerValue";
 229:   
 230:              // Set header with multiple values
 231:              string[] responseHeaderValues = new string[] { "headerValue1", "headerValue1" };
 232:              httpContext.Response.Headers["ResponseHeaderName"] = responseHeaderValues;
 233:   
 234:              // Translating ASP.NET 4's HttpContext.Response.RedirectLocation  
 235:              httpContext.Response.Headers[HeaderNames.Location] = "http://www.example.com";
 236:              // Or
 237:              httpContext.Response.Redirect("http://www.example.com");
 238:   
 239:              // GetTypedHeaders extension method provides strongly typed access to many headers
 240:              var responseHeaders = httpContext.Response.GetTypedHeaders();
 241:   
 242:              // Translating ASP.NET 4's HttpContext.Response.CacheControl 
 243:              responseHeaders.CacheControl = new CacheControlHeaderValue
 244:              {
 245:                  MaxAge = new System.TimeSpan(365, 0, 0, 0)
 246:                  // Many more properties available 
 247:              };
 248:   
 249:              // If you use .Net 4.6+, Task.CompletedTask will be a bit faster
 250:              return Task.FromResult(0);
 251:          }
 252:          #endregion
 253:   
 254:          #region snippet_SetCookies
 255:          private Task SetCookies(object context)
 256:          {
 257:              var httpContext = (HttpContext)context;
 258:   
 259:              IResponseCookies responseCookies = httpContext.Response.Cookies;
 260:   
 261:              responseCookies.Append("cookie1name", "cookie1value");
 262:              responseCookies.Append("cookie2name", "cookie2value",
 263:                  new CookieOptions { Expires = System.DateTime.Now.AddDays(5), HttpOnly = true });
 264:   
 265:              // If you use .Net 4.6+, Task.CompletedTask will be a bit faster
 266:              return Task.FromResult(0); 
 267:          }
 268:          #endregion
 269:   
 270:          // You would normally use MVC to generate HTML like this.
 271:          private string GetResponseContent()
 272:          {
 273:              return @"
 274:  <!DOCTYPE html>
 275:  <html lang=""en"">
 276:  <head>
 277:      <title>index</title>
 278:  </head>
 279:  <body>
 280:  <form action=""form.context"" method=""post"">
 281:      <input type=""text"" name=""firstname"">
 282:      <input type=""text"" name=""lastname"">
 283:      <input type=""submit"" value=""Submit"">
 284:  </form> 
 285:  </body>
 286:  </html>
 287:  ";
 288:          }
 289:      }
 290:   
 291:      public static class HttpContextDemoMiddlewareExtensions
 292:      {
 293:          public static IApplicationBuilder UseHttpContextDemoMiddleware(this IApplicationBuilder builder)
 294:          {
 295:              return builder.UseMiddleware<HttpContextDemoMiddleware>();
 296:          }
 297:      }
 298:  }

HttpContext.Request.UserAgent translates to:

[!code-csharpMain]

   1:  using Microsoft.AspNetCore.Builder;
   2:  using Microsoft.AspNetCore.Http;
   3:  using System.Collections.Generic;
   4:  using System.Threading.Tasks;
   5:  using Microsoft.Net.Http.Headers;
   6:  using Microsoft.AspNetCore.Http.Extensions;
   7:  using Microsoft.AspNetCore.Routing;
   8:   
   9:  namespace MyApp.Middleware
  10:  {
  11:      public class HttpContextDemoMiddleware
  12:      {
  13:          private readonly RequestDelegate _next;
  14:   
  15:          public HttpContextDemoMiddleware(RequestDelegate next)
  16:          {
  17:              _next = next;
  18:          }
  19:   
  20:          public async Task Invoke(HttpContext httpContext)
  21:          {
  22:              // OnStarting handlers have to be set early during request processing,
  23:              // even though they are used to create the response.
  24:   
  25:              // ----------------------
  26:              // ASP.NET 4 - HttpContext.Response.Headers  
  27:              // ASP.NET 4 - HttpContext.Response.Cookies  
  28:              // 
  29:              // Issue with all response headers is that they will not be sent 
  30:              // after anything has been written to the response body.
  31:              // To solve this, use OnStarting to set a callback that will be called 
  32:              // right before headers are sent. Set the headers in that callback.
  33:              //
  34:              // Setting a cookie results in a Set-Cookie response header.
  35:              // So use an OnStarting handler here as well.
  36:   
  37:              //>40
  38:              httpContext.Response.OnStarting(SetHeaders, state: httpContext);
  39:              httpContext.Response.OnStarting(SetCookies, state: httpContext);
  40:              //<40
  41:   
  42:              // ==================================================================
  43:              // Context
  44:   
  45:              // Unique request ID (no ASP.NET 4 counterpart)
  46:              #region snippet_Trace
  47:              string requestId = httpContext.TraceIdentifier;
  48:              #endregion
  49:   
  50:              // ASP.NET 4 - HttpContext.Items
  51:              #region snippet_Items
  52:              IDictionary<object, object> items = httpContext.Items;
  53:              #endregion
  54:   
  55:              // ==================================================================
  56:              // Request
  57:   
  58:              // ASP.NET 4 - HttpContext.Request.HttpMethod
  59:              #region snippet_Method
  60:              string httpMethod = httpContext.Request.Method;
  61:              #endregion
  62:   
  63:              // ----------
  64:   
  65:              // ASP.NET 4 - HttpContext.Request.QueryString
  66:              #region snippet_Query
  67:              IQueryCollection queryParameters = httpContext.Request.Query;
  68:   
  69:              // If no query parameter "key" used, values will have 0 items
  70:              // If single value used for a key (...?key=v1), values will have 1 item ("v1")
  71:              // If key has multiple values (...?key=v1&key=v2), values will have 2 items ("v1" and "v2")
  72:              IList<string> values = queryParameters["key"];
  73:   
  74:              // If no query parameter "key" used, value will be ""
  75:              // If single value used for a key (...?key=v1), value will be "v1"
  76:              // If key has multiple values (...?key=v1&key=v2), value will be "v1,v2"
  77:              string value = queryParameters["key"].ToString();
  78:              #endregion
  79:   
  80:              // ASP.NET 4 - HttpContext.Request.Url and HttpContext.Request.RawUrl
  81:              #region snippet_Url
  82:              // using Microsoft.AspNetCore.Http.Extensions;
  83:              var url = httpContext.Request.GetDisplayUrl();
  84:              #endregion
  85:   
  86:              // ASP.NET 4 - HttpContext.Request.IsSecureConnection
  87:              #region snippet_Secure
  88:              var isSecureConnection = httpContext.Request.IsHttps;
  89:              #endregion
  90:   
  91:              // ASP.NET 4 - HttpContext.Request.UserHostAddress
  92:              #region snippet_Host
  93:              var userHostAddress = httpContext.Connection.RemoteIpAddress?.ToString();
  94:              #endregion
  95:   
  96:              // ASP.NET 4 - HttpContext.Request.Cookies 
  97:              #region snippet_Cookies
  98:              IRequestCookieCollection cookies = httpContext.Request.Cookies;
  99:              string unknownCookieValue = cookies["unknownCookie"]; // will be null (no exception)
 100:              string knownCookieValue = cookies["cookie1name"];     // will be actual value
 101:              #endregion
 102:   
 103:              // ASP.NET 4 - HttpContext.Request.RequestContext.RouteData
 104:              // using Microsoft.AspNetCore.Routing;
 105:              #region snippet_Route
 106:              var routeValue = httpContext.GetRouteValue("key");
 107:              #endregion
 108:   
 109:              // ASP.NET 4 - HttpContext.Request.Headers
 110:              #region snippet_Headers
 111:              // using Microsoft.AspNetCore.Http.Headers;
 112:              // using Microsoft.Net.Http.Headers;
 113:   
 114:              IHeaderDictionary headersDictionary = httpContext.Request.Headers;
 115:   
 116:              // GetTypedHeaders extension method provides strongly typed access to many headers
 117:              var requestHeaders = httpContext.Request.GetTypedHeaders();
 118:              CacheControlHeaderValue cacheControlHeaderValue = requestHeaders.CacheControl;
 119:   
 120:              // For unknown header, unknownheaderValues has zero items and unknownheaderValue is ""
 121:              IList<string> unknownheaderValues = headersDictionary["unknownheader"];
 122:              string unknownheaderValue = headersDictionary["unknownheader"].ToString();
 123:   
 124:              // For known header, knownheaderValues has 1 item and knownheaderValue is the value
 125:              IList<string> knownheaderValues = headersDictionary[HeaderNames.AcceptLanguage];
 126:              string knownheaderValue = headersDictionary[HeaderNames.AcceptLanguage].ToString();
 127:              #endregion
 128:   
 129:              // ASP.NET 4 - HttpContext.Request.UserAgent
 130:              #region snippet_Agent
 131:              string userAgent = headersDictionary[HeaderNames.UserAgent].ToString();
 132:              #endregion
 133:   
 134:              // ASP.NET 4 - HttpContext.Request.UrlReferrer
 135:              #region snippet_Referrer
 136:              string urlReferrer = headersDictionary[HeaderNames.Referer].ToString();
 137:              #endregion
 138:   
 139:              // ASP.NET 4 - HttpContext.Request.ContentType 
 140:              #region snippet_Type
 141:              // using Microsoft.Net.Http.Headers;
 142:   
 143:              MediaTypeHeaderValue mediaHeaderValue = requestHeaders.ContentType;
 144:              string contentType = mediaHeaderValue?.MediaType;   // ex. application/x-www-form-urlencoded
 145:              string contentMainType = mediaHeaderValue?.Type;    // ex. application
 146:              string contentSubType = mediaHeaderValue?.SubType;  // ex. x-www-form-urlencoded
 147:   
 148:              System.Text.Encoding requestEncoding = mediaHeaderValue?.Encoding;
 149:              #endregion
 150:   
 151:              // ASP.NET 4 - HttpContext.Request.Form 
 152:              #region snippet_Form
 153:              if (httpContext.Request.HasFormContentType)
 154:              {
 155:                  IFormCollection form;
 156:   
 157:                  form = httpContext.Request.Form; // sync
 158:                  // Or
 159:                  form = await httpContext.Request.ReadFormAsync(); // async
 160:   
 161:                  string firstName = form["firstname"];
 162:                  string lastName = form["lastname"];
 163:              }
 164:              #endregion
 165:   
 166:              // ----------
 167:              // See 
 168:              // http://stackoverflow.com/questions/31389781/read-body-twice-in-asp-net-5/
 169:   
 170:              // ASP.NET 4 - HttpContext.Request.InputStream
 171:              // Unlike reading the form, reading the raw body is not from a buffer.
 172:              // So you can only do this once per request.
 173:              // 
 174:              // If you need to read the body multiple times per request, see
 175:              // http://stackoverflow.com/questions/31389781/read-body-twice-in-asp-net-5/
 176:   
 177:              #region snippet_Input
 178:              string inputBody;
 179:              using (var reader = new System.IO.StreamReader(
 180:                  httpContext.Request.Body, System.Text.Encoding.UTF8))
 181:              {
 182:                  inputBody = reader.ReadToEnd();
 183:              }
 184:              #endregion
 185:   
 186:              // Use this middleware as a handler, so no call to 
 187:              // await _next.Invoke(aspnetCoreHttpContext);
 188:   
 189:              // ==================================================================
 190:              // Response
 191:   
 192:              // ASP.NET 4 - HttpContext.Response.Status  
 193:              // ASP.NET 4 - HttpContext.Response.StatusDescription (obsolete, removed from HTTP/2) 
 194:              #region snippet_Status
 195:              // using Microsoft.AspNetCore.Http;
 196:              httpContext.Response.StatusCode = StatusCodes.Status200OK;
 197:              #endregion
 198:   
 199:              // ASP.NET 4 - HttpContext.Response.ContentEncoding and HttpContext.Response.ContentType  
 200:              #region snippet_RespType
 201:              // using Microsoft.Net.Http.Headers;
 202:              var mediaType = new MediaTypeHeaderValue("application/json");
 203:              mediaType.Encoding = System.Text.Encoding.UTF8;
 204:              httpContext.Response.ContentType = mediaType.ToString();
 205:              #endregion
 206:   
 207:              // ASP.NET 4 - HttpContext.Response.ContentType only 
 208:              #region snippet_RespTypeOnly
 209:              httpContext.Response.ContentType = "text/html";
 210:              #endregion
 211:   
 212:              // ASP.NET 4 - HttpContext.Response.Output  
 213:              #region  snippet_Output
 214:              string responseContent = GetResponseContent();
 215:              await httpContext.Response.WriteAsync(responseContent);
 216:              #endregion
 217:          }
 218:   
 219:          #region snippet_SetHeaders
 220:          // using Microsoft.AspNet.Http.Headers;
 221:          // using Microsoft.Net.Http.Headers;
 222:   
 223:          private Task SetHeaders(object context)
 224:          {
 225:              var httpContext = (HttpContext)context;
 226:   
 227:              // Set header with single value
 228:              httpContext.Response.Headers["ResponseHeaderName"] = "headerValue";
 229:   
 230:              // Set header with multiple values
 231:              string[] responseHeaderValues = new string[] { "headerValue1", "headerValue1" };
 232:              httpContext.Response.Headers["ResponseHeaderName"] = responseHeaderValues;
 233:   
 234:              // Translating ASP.NET 4's HttpContext.Response.RedirectLocation  
 235:              httpContext.Response.Headers[HeaderNames.Location] = "http://www.example.com";
 236:              // Or
 237:              httpContext.Response.Redirect("http://www.example.com");
 238:   
 239:              // GetTypedHeaders extension method provides strongly typed access to many headers
 240:              var responseHeaders = httpContext.Response.GetTypedHeaders();
 241:   
 242:              // Translating ASP.NET 4's HttpContext.Response.CacheControl 
 243:              responseHeaders.CacheControl = new CacheControlHeaderValue
 244:              {
 245:                  MaxAge = new System.TimeSpan(365, 0, 0, 0)
 246:                  // Many more properties available 
 247:              };
 248:   
 249:              // If you use .Net 4.6+, Task.CompletedTask will be a bit faster
 250:              return Task.FromResult(0);
 251:          }
 252:          #endregion
 253:   
 254:          #region snippet_SetCookies
 255:          private Task SetCookies(object context)
 256:          {
 257:              var httpContext = (HttpContext)context;
 258:   
 259:              IResponseCookies responseCookies = httpContext.Response.Cookies;
 260:   
 261:              responseCookies.Append("cookie1name", "cookie1value");
 262:              responseCookies.Append("cookie2name", "cookie2value",
 263:                  new CookieOptions { Expires = System.DateTime.Now.AddDays(5), HttpOnly = true });
 264:   
 265:              // If you use .Net 4.6+, Task.CompletedTask will be a bit faster
 266:              return Task.FromResult(0); 
 267:          }
 268:          #endregion
 269:   
 270:          // You would normally use MVC to generate HTML like this.
 271:          private string GetResponseContent()
 272:          {
 273:              return @"
 274:  <!DOCTYPE html>
 275:  <html lang=""en"">
 276:  <head>
 277:      <title>index</title>
 278:  </head>
 279:  <body>
 280:  <form action=""form.context"" method=""post"">
 281:      <input type=""text"" name=""firstname"">
 282:      <input type=""text"" name=""lastname"">
 283:      <input type=""submit"" value=""Submit"">
 284:  </form> 
 285:  </body>
 286:  </html>
 287:  ";
 288:          }
 289:      }
 290:   
 291:      public static class HttpContextDemoMiddlewareExtensions
 292:      {
 293:          public static IApplicationBuilder UseHttpContextDemoMiddleware(this IApplicationBuilder builder)
 294:          {
 295:              return builder.UseMiddleware<HttpContextDemoMiddleware>();
 296:          }
 297:      }
 298:  }

HttpContext.Request.UrlReferrer translates to:

[!code-csharpMain]

   1:  using Microsoft.AspNetCore.Builder;
   2:  using Microsoft.AspNetCore.Http;
   3:  using System.Collections.Generic;
   4:  using System.Threading.Tasks;
   5:  using Microsoft.Net.Http.Headers;
   6:  using Microsoft.AspNetCore.Http.Extensions;
   7:  using Microsoft.AspNetCore.Routing;
   8:   
   9:  namespace MyApp.Middleware
  10:  {
  11:      public class HttpContextDemoMiddleware
  12:      {
  13:          private readonly RequestDelegate _next;
  14:   
  15:          public HttpContextDemoMiddleware(RequestDelegate next)
  16:          {
  17:              _next = next;
  18:          }
  19:   
  20:          public async Task Invoke(HttpContext httpContext)
  21:          {
  22:              // OnStarting handlers have to be set early during request processing,
  23:              // even though they are used to create the response.
  24:   
  25:              // ----------------------
  26:              // ASP.NET 4 - HttpContext.Response.Headers  
  27:              // ASP.NET 4 - HttpContext.Response.Cookies  
  28:              // 
  29:              // Issue with all response headers is that they will not be sent 
  30:              // after anything has been written to the response body.
  31:              // To solve this, use OnStarting to set a callback that will be called 
  32:              // right before headers are sent. Set the headers in that callback.
  33:              //
  34:              // Setting a cookie results in a Set-Cookie response header.
  35:              // So use an OnStarting handler here as well.
  36:   
  37:              //>40
  38:              httpContext.Response.OnStarting(SetHeaders, state: httpContext);
  39:              httpContext.Response.OnStarting(SetCookies, state: httpContext);
  40:              //<40
  41:   
  42:              // ==================================================================
  43:              // Context
  44:   
  45:              // Unique request ID (no ASP.NET 4 counterpart)
  46:              #region snippet_Trace
  47:              string requestId = httpContext.TraceIdentifier;
  48:              #endregion
  49:   
  50:              // ASP.NET 4 - HttpContext.Items
  51:              #region snippet_Items
  52:              IDictionary<object, object> items = httpContext.Items;
  53:              #endregion
  54:   
  55:              // ==================================================================
  56:              // Request
  57:   
  58:              // ASP.NET 4 - HttpContext.Request.HttpMethod
  59:              #region snippet_Method
  60:              string httpMethod = httpContext.Request.Method;
  61:              #endregion
  62:   
  63:              // ----------
  64:   
  65:              // ASP.NET 4 - HttpContext.Request.QueryString
  66:              #region snippet_Query
  67:              IQueryCollection queryParameters = httpContext.Request.Query;
  68:   
  69:              // If no query parameter "key" used, values will have 0 items
  70:              // If single value used for a key (...?key=v1), values will have 1 item ("v1")
  71:              // If key has multiple values (...?key=v1&key=v2), values will have 2 items ("v1" and "v2")
  72:              IList<string> values = queryParameters["key"];
  73:   
  74:              // If no query parameter "key" used, value will be ""
  75:              // If single value used for a key (...?key=v1), value will be "v1"
  76:              // If key has multiple values (...?key=v1&key=v2), value will be "v1,v2"
  77:              string value = queryParameters["key"].ToString();
  78:              #endregion
  79:   
  80:              // ASP.NET 4 - HttpContext.Request.Url and HttpContext.Request.RawUrl
  81:              #region snippet_Url
  82:              // using Microsoft.AspNetCore.Http.Extensions;
  83:              var url = httpContext.Request.GetDisplayUrl();
  84:              #endregion
  85:   
  86:              // ASP.NET 4 - HttpContext.Request.IsSecureConnection
  87:              #region snippet_Secure
  88:              var isSecureConnection = httpContext.Request.IsHttps;
  89:              #endregion
  90:   
  91:              // ASP.NET 4 - HttpContext.Request.UserHostAddress
  92:              #region snippet_Host
  93:              var userHostAddress = httpContext.Connection.RemoteIpAddress?.ToString();
  94:              #endregion
  95:   
  96:              // ASP.NET 4 - HttpContext.Request.Cookies 
  97:              #region snippet_Cookies
  98:              IRequestCookieCollection cookies = httpContext.Request.Cookies;
  99:              string unknownCookieValue = cookies["unknownCookie"]; // will be null (no exception)
 100:              string knownCookieValue = cookies["cookie1name"];     // will be actual value
 101:              #endregion
 102:   
 103:              // ASP.NET 4 - HttpContext.Request.RequestContext.RouteData
 104:              // using Microsoft.AspNetCore.Routing;
 105:              #region snippet_Route
 106:              var routeValue = httpContext.GetRouteValue("key");
 107:              #endregion
 108:   
 109:              // ASP.NET 4 - HttpContext.Request.Headers
 110:              #region snippet_Headers
 111:              // using Microsoft.AspNetCore.Http.Headers;
 112:              // using Microsoft.Net.Http.Headers;
 113:   
 114:              IHeaderDictionary headersDictionary = httpContext.Request.Headers;
 115:   
 116:              // GetTypedHeaders extension method provides strongly typed access to many headers
 117:              var requestHeaders = httpContext.Request.GetTypedHeaders();
 118:              CacheControlHeaderValue cacheControlHeaderValue = requestHeaders.CacheControl;
 119:   
 120:              // For unknown header, unknownheaderValues has zero items and unknownheaderValue is ""
 121:              IList<string> unknownheaderValues = headersDictionary["unknownheader"];
 122:              string unknownheaderValue = headersDictionary["unknownheader"].ToString();
 123:   
 124:              // For known header, knownheaderValues has 1 item and knownheaderValue is the value
 125:              IList<string> knownheaderValues = headersDictionary[HeaderNames.AcceptLanguage];
 126:              string knownheaderValue = headersDictionary[HeaderNames.AcceptLanguage].ToString();
 127:              #endregion
 128:   
 129:              // ASP.NET 4 - HttpContext.Request.UserAgent
 130:              #region snippet_Agent
 131:              string userAgent = headersDictionary[HeaderNames.UserAgent].ToString();
 132:              #endregion
 133:   
 134:              // ASP.NET 4 - HttpContext.Request.UrlReferrer
 135:              #region snippet_Referrer
 136:              string urlReferrer = headersDictionary[HeaderNames.Referer].ToString();
 137:              #endregion
 138:   
 139:              // ASP.NET 4 - HttpContext.Request.ContentType 
 140:              #region snippet_Type
 141:              // using Microsoft.Net.Http.Headers;
 142:   
 143:              MediaTypeHeaderValue mediaHeaderValue = requestHeaders.ContentType;
 144:              string contentType = mediaHeaderValue?.MediaType;   // ex. application/x-www-form-urlencoded
 145:              string contentMainType = mediaHeaderValue?.Type;    // ex. application
 146:              string contentSubType = mediaHeaderValue?.SubType;  // ex. x-www-form-urlencoded
 147:   
 148:              System.Text.Encoding requestEncoding = mediaHeaderValue?.Encoding;
 149:              #endregion
 150:   
 151:              // ASP.NET 4 - HttpContext.Request.Form 
 152:              #region snippet_Form
 153:              if (httpContext.Request.HasFormContentType)
 154:              {
 155:                  IFormCollection form;
 156:   
 157:                  form = httpContext.Request.Form; // sync
 158:                  // Or
 159:                  form = await httpContext.Request.ReadFormAsync(); // async
 160:   
 161:                  string firstName = form["firstname"];
 162:                  string lastName = form["lastname"];
 163:              }
 164:              #endregion
 165:   
 166:              // ----------
 167:              // See 
 168:              // http://stackoverflow.com/questions/31389781/read-body-twice-in-asp-net-5/
 169:   
 170:              // ASP.NET 4 - HttpContext.Request.InputStream
 171:              // Unlike reading the form, reading the raw body is not from a buffer.
 172:              // So you can only do this once per request.
 173:              // 
 174:              // If you need to read the body multiple times per request, see
 175:              // http://stackoverflow.com/questions/31389781/read-body-twice-in-asp-net-5/
 176:   
 177:              #region snippet_Input
 178:              string inputBody;
 179:              using (var reader = new System.IO.StreamReader(
 180:                  httpContext.Request.Body, System.Text.Encoding.UTF8))
 181:              {
 182:                  inputBody = reader.ReadToEnd();
 183:              }
 184:              #endregion
 185:   
 186:              // Use this middleware as a handler, so no call to 
 187:              // await _next.Invoke(aspnetCoreHttpContext);
 188:   
 189:              // ==================================================================
 190:              // Response
 191:   
 192:              // ASP.NET 4 - HttpContext.Response.Status  
 193:              // ASP.NET 4 - HttpContext.Response.StatusDescription (obsolete, removed from HTTP/2) 
 194:              #region snippet_Status
 195:              // using Microsoft.AspNetCore.Http;
 196:              httpContext.Response.StatusCode = StatusCodes.Status200OK;
 197:              #endregion
 198:   
 199:              // ASP.NET 4 - HttpContext.Response.ContentEncoding and HttpContext.Response.ContentType  
 200:              #region snippet_RespType
 201:              // using Microsoft.Net.Http.Headers;
 202:              var mediaType = new MediaTypeHeaderValue("application/json");
 203:              mediaType.Encoding = System.Text.Encoding.UTF8;
 204:              httpContext.Response.ContentType = mediaType.ToString();
 205:              #endregion
 206:   
 207:              // ASP.NET 4 - HttpContext.Response.ContentType only 
 208:              #region snippet_RespTypeOnly
 209:              httpContext.Response.ContentType = "text/html";
 210:              #endregion
 211:   
 212:              // ASP.NET 4 - HttpContext.Response.Output  
 213:              #region  snippet_Output
 214:              string responseContent = GetResponseContent();
 215:              await httpContext.Response.WriteAsync(responseContent);
 216:              #endregion
 217:          }
 218:   
 219:          #region snippet_SetHeaders
 220:          // using Microsoft.AspNet.Http.Headers;
 221:          // using Microsoft.Net.Http.Headers;
 222:   
 223:          private Task SetHeaders(object context)
 224:          {
 225:              var httpContext = (HttpContext)context;
 226:   
 227:              // Set header with single value
 228:              httpContext.Response.Headers["ResponseHeaderName"] = "headerValue";
 229:   
 230:              // Set header with multiple values
 231:              string[] responseHeaderValues = new string[] { "headerValue1", "headerValue1" };
 232:              httpContext.Response.Headers["ResponseHeaderName"] = responseHeaderValues;
 233:   
 234:              // Translating ASP.NET 4's HttpContext.Response.RedirectLocation  
 235:              httpContext.Response.Headers[HeaderNames.Location] = "http://www.example.com";
 236:              // Or
 237:              httpContext.Response.Redirect("http://www.example.com");
 238:   
 239:              // GetTypedHeaders extension method provides strongly typed access to many headers
 240:              var responseHeaders = httpContext.Response.GetTypedHeaders();
 241:   
 242:              // Translating ASP.NET 4's HttpContext.Response.CacheControl 
 243:              responseHeaders.CacheControl = new CacheControlHeaderValue
 244:              {
 245:                  MaxAge = new System.TimeSpan(365, 0, 0, 0)
 246:                  // Many more properties available 
 247:              };
 248:   
 249:              // If you use .Net 4.6+, Task.CompletedTask will be a bit faster
 250:              return Task.FromResult(0);
 251:          }
 252:          #endregion
 253:   
 254:          #region snippet_SetCookies
 255:          private Task SetCookies(object context)
 256:          {
 257:              var httpContext = (HttpContext)context;
 258:   
 259:              IResponseCookies responseCookies = httpContext.Response.Cookies;
 260:   
 261:              responseCookies.Append("cookie1name", "cookie1value");
 262:              responseCookies.Append("cookie2name", "cookie2value",
 263:                  new CookieOptions { Expires = System.DateTime.Now.AddDays(5), HttpOnly = true });
 264:   
 265:              // If you use .Net 4.6+, Task.CompletedTask will be a bit faster
 266:              return Task.FromResult(0); 
 267:          }
 268:          #endregion
 269:   
 270:          // You would normally use MVC to generate HTML like this.
 271:          private string GetResponseContent()
 272:          {
 273:              return @"
 274:  <!DOCTYPE html>
 275:  <html lang=""en"">
 276:  <head>
 277:      <title>index</title>
 278:  </head>
 279:  <body>
 280:  <form action=""form.context"" method=""post"">
 281:      <input type=""text"" name=""firstname"">
 282:      <input type=""text"" name=""lastname"">
 283:      <input type=""submit"" value=""Submit"">
 284:  </form> 
 285:  </body>
 286:  </html>
 287:  ";
 288:          }
 289:      }
 290:   
 291:      public static class HttpContextDemoMiddlewareExtensions
 292:      {
 293:          public static IApplicationBuilder UseHttpContextDemoMiddleware(this IApplicationBuilder builder)
 294:          {
 295:              return builder.UseMiddleware<HttpContextDemoMiddleware>();
 296:          }
 297:      }
 298:  }

HttpContext.Request.ContentType translates to:

[!code-csharpMain]

   1:  using Microsoft.AspNetCore.Builder;
   2:  using Microsoft.AspNetCore.Http;
   3:  using System.Collections.Generic;
   4:  using System.Threading.Tasks;
   5:  using Microsoft.Net.Http.Headers;
   6:  using Microsoft.AspNetCore.Http.Extensions;
   7:  using Microsoft.AspNetCore.Routing;
   8:   
   9:  namespace MyApp.Middleware
  10:  {
  11:      public class HttpContextDemoMiddleware
  12:      {
  13:          private readonly RequestDelegate _next;
  14:   
  15:          public HttpContextDemoMiddleware(RequestDelegate next)
  16:          {
  17:              _next = next;
  18:          }
  19:   
  20:          public async Task Invoke(HttpContext httpContext)
  21:          {
  22:              // OnStarting handlers have to be set early during request processing,
  23:              // even though they are used to create the response.
  24:   
  25:              // ----------------------
  26:              // ASP.NET 4 - HttpContext.Response.Headers  
  27:              // ASP.NET 4 - HttpContext.Response.Cookies  
  28:              // 
  29:              // Issue with all response headers is that they will not be sent 
  30:              // after anything has been written to the response body.
  31:              // To solve this, use OnStarting to set a callback that will be called 
  32:              // right before headers are sent. Set the headers in that callback.
  33:              //
  34:              // Setting a cookie results in a Set-Cookie response header.
  35:              // So use an OnStarting handler here as well.
  36:   
  37:              //>40
  38:              httpContext.Response.OnStarting(SetHeaders, state: httpContext);
  39:              httpContext.Response.OnStarting(SetCookies, state: httpContext);
  40:              //<40
  41:   
  42:              // ==================================================================
  43:              // Context
  44:   
  45:              // Unique request ID (no ASP.NET 4 counterpart)
  46:              #region snippet_Trace
  47:              string requestId = httpContext.TraceIdentifier;
  48:              #endregion
  49:   
  50:              // ASP.NET 4 - HttpContext.Items
  51:              #region snippet_Items
  52:              IDictionary<object, object> items = httpContext.Items;
  53:              #endregion
  54:   
  55:              // ==================================================================
  56:              // Request
  57:   
  58:              // ASP.NET 4 - HttpContext.Request.HttpMethod
  59:              #region snippet_Method
  60:              string httpMethod = httpContext.Request.Method;
  61:              #endregion
  62:   
  63:              // ----------
  64:   
  65:              // ASP.NET 4 - HttpContext.Request.QueryString
  66:              #region snippet_Query
  67:              IQueryCollection queryParameters = httpContext.Request.Query;
  68:   
  69:              // If no query parameter "key" used, values will have 0 items
  70:              // If single value used for a key (...?key=v1), values will have 1 item ("v1")
  71:              // If key has multiple values (...?key=v1&key=v2), values will have 2 items ("v1" and "v2")
  72:              IList<string> values = queryParameters["key"];
  73:   
  74:              // If no query parameter "key" used, value will be ""
  75:              // If single value used for a key (...?key=v1), value will be "v1"
  76:              // If key has multiple values (...?key=v1&key=v2), value will be "v1,v2"
  77:              string value = queryParameters["key"].ToString();
  78:              #endregion
  79:   
  80:              // ASP.NET 4 - HttpContext.Request.Url and HttpContext.Request.RawUrl
  81:              #region snippet_Url
  82:              // using Microsoft.AspNetCore.Http.Extensions;
  83:              var url = httpContext.Request.GetDisplayUrl();
  84:              #endregion
  85:   
  86:              // ASP.NET 4 - HttpContext.Request.IsSecureConnection
  87:              #region snippet_Secure
  88:              var isSecureConnection = httpContext.Request.IsHttps;
  89:              #endregion
  90:   
  91:              // ASP.NET 4 - HttpContext.Request.UserHostAddress
  92:              #region snippet_Host
  93:              var userHostAddress = httpContext.Connection.RemoteIpAddress?.ToString();
  94:              #endregion
  95:   
  96:              // ASP.NET 4 - HttpContext.Request.Cookies 
  97:              #region snippet_Cookies
  98:              IRequestCookieCollection cookies = httpContext.Request.Cookies;
  99:              string unknownCookieValue = cookies["unknownCookie"]; // will be null (no exception)
 100:              string knownCookieValue = cookies["cookie1name"];     // will be actual value
 101:              #endregion
 102:   
 103:              // ASP.NET 4 - HttpContext.Request.RequestContext.RouteData
 104:              // using Microsoft.AspNetCore.Routing;
 105:              #region snippet_Route
 106:              var routeValue = httpContext.GetRouteValue("key");
 107:              #endregion
 108:   
 109:              // ASP.NET 4 - HttpContext.Request.Headers
 110:              #region snippet_Headers
 111:              // using Microsoft.AspNetCore.Http.Headers;
 112:              // using Microsoft.Net.Http.Headers;
 113:   
 114:              IHeaderDictionary headersDictionary = httpContext.Request.Headers;
 115:   
 116:              // GetTypedHeaders extension method provides strongly typed access to many headers
 117:              var requestHeaders = httpContext.Request.GetTypedHeaders();
 118:              CacheControlHeaderValue cacheControlHeaderValue = requestHeaders.CacheControl;
 119:   
 120:              // For unknown header, unknownheaderValues has zero items and unknownheaderValue is ""
 121:              IList<string> unknownheaderValues = headersDictionary["unknownheader"];
 122:              string unknownheaderValue = headersDictionary["unknownheader"].ToString();
 123:   
 124:              // For known header, knownheaderValues has 1 item and knownheaderValue is the value
 125:              IList<string> knownheaderValues = headersDictionary[HeaderNames.AcceptLanguage];
 126:              string knownheaderValue = headersDictionary[HeaderNames.AcceptLanguage].ToString();
 127:              #endregion
 128:   
 129:              // ASP.NET 4 - HttpContext.Request.UserAgent
 130:              #region snippet_Agent
 131:              string userAgent = headersDictionary[HeaderNames.UserAgent].ToString();
 132:              #endregion
 133:   
 134:              // ASP.NET 4 - HttpContext.Request.UrlReferrer
 135:              #region snippet_Referrer
 136:              string urlReferrer = headersDictionary[HeaderNames.Referer].ToString();
 137:              #endregion
 138:   
 139:              // ASP.NET 4 - HttpContext.Request.ContentType 
 140:              #region snippet_Type
 141:              // using Microsoft.Net.Http.Headers;
 142:   
 143:              MediaTypeHeaderValue mediaHeaderValue = requestHeaders.ContentType;
 144:              string contentType = mediaHeaderValue?.MediaType;   // ex. application/x-www-form-urlencoded
 145:              string contentMainType = mediaHeaderValue?.Type;    // ex. application
 146:              string contentSubType = mediaHeaderValue?.SubType;  // ex. x-www-form-urlencoded
 147:   
 148:              System.Text.Encoding requestEncoding = mediaHeaderValue?.Encoding;
 149:              #endregion
 150:   
 151:              // ASP.NET 4 - HttpContext.Request.Form 
 152:              #region snippet_Form
 153:              if (httpContext.Request.HasFormContentType)
 154:              {
 155:                  IFormCollection form;
 156:   
 157:                  form = httpContext.Request.Form; // sync
 158:                  // Or
 159:                  form = await httpContext.Request.ReadFormAsync(); // async
 160:   
 161:                  string firstName = form["firstname"];
 162:                  string lastName = form["lastname"];
 163:              }
 164:              #endregion
 165:   
 166:              // ----------
 167:              // See 
 168:              // http://stackoverflow.com/questions/31389781/read-body-twice-in-asp-net-5/
 169:   
 170:              // ASP.NET 4 - HttpContext.Request.InputStream
 171:              // Unlike reading the form, reading the raw body is not from a buffer.
 172:              // So you can only do this once per request.
 173:              // 
 174:              // If you need to read the body multiple times per request, see
 175:              // http://stackoverflow.com/questions/31389781/read-body-twice-in-asp-net-5/
 176:   
 177:              #region snippet_Input
 178:              string inputBody;
 179:              using (var reader = new System.IO.StreamReader(
 180:                  httpContext.Request.Body, System.Text.Encoding.UTF8))
 181:              {
 182:                  inputBody = reader.ReadToEnd();
 183:              }
 184:              #endregion
 185:   
 186:              // Use this middleware as a handler, so no call to 
 187:              // await _next.Invoke(aspnetCoreHttpContext);
 188:   
 189:              // ==================================================================
 190:              // Response
 191:   
 192:              // ASP.NET 4 - HttpContext.Response.Status  
 193:              // ASP.NET 4 - HttpContext.Response.StatusDescription (obsolete, removed from HTTP/2) 
 194:              #region snippet_Status
 195:              // using Microsoft.AspNetCore.Http;
 196:              httpContext.Response.StatusCode = StatusCodes.Status200OK;
 197:              #endregion
 198:   
 199:              // ASP.NET 4 - HttpContext.Response.ContentEncoding and HttpContext.Response.ContentType  
 200:              #region snippet_RespType
 201:              // using Microsoft.Net.Http.Headers;
 202:              var mediaType = new MediaTypeHeaderValue("application/json");
 203:              mediaType.Encoding = System.Text.Encoding.UTF8;
 204:              httpContext.Response.ContentType = mediaType.ToString();
 205:              #endregion
 206:   
 207:              // ASP.NET 4 - HttpContext.Response.ContentType only 
 208:              #region snippet_RespTypeOnly
 209:              httpContext.Response.ContentType = "text/html";
 210:              #endregion
 211:   
 212:              // ASP.NET 4 - HttpContext.Response.Output  
 213:              #region  snippet_Output
 214:              string responseContent = GetResponseContent();
 215:              await httpContext.Response.WriteAsync(responseContent);
 216:              #endregion
 217:          }
 218:   
 219:          #region snippet_SetHeaders
 220:          // using Microsoft.AspNet.Http.Headers;
 221:          // using Microsoft.Net.Http.Headers;
 222:   
 223:          private Task SetHeaders(object context)
 224:          {
 225:              var httpContext = (HttpContext)context;
 226:   
 227:              // Set header with single value
 228:              httpContext.Response.Headers["ResponseHeaderName"] = "headerValue";
 229:   
 230:              // Set header with multiple values
 231:              string[] responseHeaderValues = new string[] { "headerValue1", "headerValue1" };
 232:              httpContext.Response.Headers["ResponseHeaderName"] = responseHeaderValues;
 233:   
 234:              // Translating ASP.NET 4's HttpContext.Response.RedirectLocation  
 235:              httpContext.Response.Headers[HeaderNames.Location] = "http://www.example.com";
 236:              // Or
 237:              httpContext.Response.Redirect("http://www.example.com");
 238:   
 239:              // GetTypedHeaders extension method provides strongly typed access to many headers
 240:              var responseHeaders = httpContext.Response.GetTypedHeaders();
 241:   
 242:              // Translating ASP.NET 4's HttpContext.Response.CacheControl 
 243:              responseHeaders.CacheControl = new CacheControlHeaderValue
 244:              {
 245:                  MaxAge = new System.TimeSpan(365, 0, 0, 0)
 246:                  // Many more properties available 
 247:              };
 248:   
 249:              // If you use .Net 4.6+, Task.CompletedTask will be a bit faster
 250:              return Task.FromResult(0);
 251:          }
 252:          #endregion
 253:   
 254:          #region snippet_SetCookies
 255:          private Task SetCookies(object context)
 256:          {
 257:              var httpContext = (HttpContext)context;
 258:   
 259:              IResponseCookies responseCookies = httpContext.Response.Cookies;
 260:   
 261:              responseCookies.Append("cookie1name", "cookie1value");
 262:              responseCookies.Append("cookie2name", "cookie2value",
 263:                  new CookieOptions { Expires = System.DateTime.Now.AddDays(5), HttpOnly = true });
 264:   
 265:              // If you use .Net 4.6+, Task.CompletedTask will be a bit faster
 266:              return Task.FromResult(0); 
 267:          }
 268:          #endregion
 269:   
 270:          // You would normally use MVC to generate HTML like this.
 271:          private string GetResponseContent()
 272:          {
 273:              return @"
 274:  <!DOCTYPE html>
 275:  <html lang=""en"">
 276:  <head>
 277:      <title>index</title>
 278:  </head>
 279:  <body>
 280:  <form action=""form.context"" method=""post"">
 281:      <input type=""text"" name=""firstname"">
 282:      <input type=""text"" name=""lastname"">
 283:      <input type=""submit"" value=""Submit"">
 284:  </form> 
 285:  </body>
 286:  </html>
 287:  ";
 288:          }
 289:      }
 290:   
 291:      public static class HttpContextDemoMiddlewareExtensions
 292:      {
 293:          public static IApplicationBuilder UseHttpContextDemoMiddleware(this IApplicationBuilder builder)
 294:          {
 295:              return builder.UseMiddleware<HttpContextDemoMiddleware>();
 296:          }
 297:      }
 298:  }

HttpContext.Request.Form translates to:

[!code-csharpMain]

   1:  using Microsoft.AspNetCore.Builder;
   2:  using Microsoft.AspNetCore.Http;
   3:  using System.Collections.Generic;
   4:  using System.Threading.Tasks;
   5:  using Microsoft.Net.Http.Headers;
   6:  using Microsoft.AspNetCore.Http.Extensions;
   7:  using Microsoft.AspNetCore.Routing;
   8:   
   9:  namespace MyApp.Middleware
  10:  {
  11:      public class HttpContextDemoMiddleware
  12:      {
  13:          private readonly RequestDelegate _next;
  14:   
  15:          public HttpContextDemoMiddleware(RequestDelegate next)
  16:          {
  17:              _next = next;
  18:          }
  19:   
  20:          public async Task Invoke(HttpContext httpContext)
  21:          {
  22:              // OnStarting handlers have to be set early during request processing,
  23:              // even though they are used to create the response.
  24:   
  25:              // ----------------------
  26:              // ASP.NET 4 - HttpContext.Response.Headers  
  27:              // ASP.NET 4 - HttpContext.Response.Cookies  
  28:              // 
  29:              // Issue with all response headers is that they will not be sent 
  30:              // after anything has been written to the response body.
  31:              // To solve this, use OnStarting to set a callback that will be called 
  32:              // right before headers are sent. Set the headers in that callback.
  33:              //
  34:              // Setting a cookie results in a Set-Cookie response header.
  35:              // So use an OnStarting handler here as well.
  36:   
  37:              //>40
  38:              httpContext.Response.OnStarting(SetHeaders, state: httpContext);
  39:              httpContext.Response.OnStarting(SetCookies, state: httpContext);
  40:              //<40
  41:   
  42:              // ==================================================================
  43:              // Context
  44:   
  45:              // Unique request ID (no ASP.NET 4 counterpart)
  46:              #region snippet_Trace
  47:              string requestId = httpContext.TraceIdentifier;
  48:              #endregion
  49:   
  50:              // ASP.NET 4 - HttpContext.Items
  51:              #region snippet_Items
  52:              IDictionary<object, object> items = httpContext.Items;
  53:              #endregion
  54:   
  55:              // ==================================================================
  56:              // Request
  57:   
  58:              // ASP.NET 4 - HttpContext.Request.HttpMethod
  59:              #region snippet_Method
  60:              string httpMethod = httpContext.Request.Method;
  61:              #endregion
  62:   
  63:              // ----------
  64:   
  65:              // ASP.NET 4 - HttpContext.Request.QueryString
  66:              #region snippet_Query
  67:              IQueryCollection queryParameters = httpContext.Request.Query;
  68:   
  69:              // If no query parameter "key" used, values will have 0 items
  70:              // If single value used for a key (...?key=v1), values will have 1 item ("v1")
  71:              // If key has multiple values (...?key=v1&key=v2), values will have 2 items ("v1" and "v2")
  72:              IList<string> values = queryParameters["key"];
  73:   
  74:              // If no query parameter "key" used, value will be ""
  75:              // If single value used for a key (...?key=v1), value will be "v1"
  76:              // If key has multiple values (...?key=v1&key=v2), value will be "v1,v2"
  77:              string value = queryParameters["key"].ToString();
  78:              #endregion
  79:   
  80:              // ASP.NET 4 - HttpContext.Request.Url and HttpContext.Request.RawUrl
  81:              #region snippet_Url
  82:              // using Microsoft.AspNetCore.Http.Extensions;
  83:              var url = httpContext.Request.GetDisplayUrl();
  84:              #endregion
  85:   
  86:              // ASP.NET 4 - HttpContext.Request.IsSecureConnection
  87:              #region snippet_Secure
  88:              var isSecureConnection = httpContext.Request.IsHttps;
  89:              #endregion
  90:   
  91:              // ASP.NET 4 - HttpContext.Request.UserHostAddress
  92:              #region snippet_Host
  93:              var userHostAddress = httpContext.Connection.RemoteIpAddress?.ToString();
  94:              #endregion
  95:   
  96:              // ASP.NET 4 - HttpContext.Request.Cookies 
  97:              #region snippet_Cookies
  98:              IRequestCookieCollection cookies = httpContext.Request.Cookies;
  99:              string unknownCookieValue = cookies["unknownCookie"]; // will be null (no exception)
 100:              string knownCookieValue = cookies["cookie1name"];     // will be actual value
 101:              #endregion
 102:   
 103:              // ASP.NET 4 - HttpContext.Request.RequestContext.RouteData
 104:              // using Microsoft.AspNetCore.Routing;
 105:              #region snippet_Route
 106:              var routeValue = httpContext.GetRouteValue("key");
 107:              #endregion
 108:   
 109:              // ASP.NET 4 - HttpContext.Request.Headers
 110:              #region snippet_Headers
 111:              // using Microsoft.AspNetCore.Http.Headers;
 112:              // using Microsoft.Net.Http.Headers;
 113:   
 114:              IHeaderDictionary headersDictionary = httpContext.Request.Headers;
 115:   
 116:              // GetTypedHeaders extension method provides strongly typed access to many headers
 117:              var requestHeaders = httpContext.Request.GetTypedHeaders();
 118:              CacheControlHeaderValue cacheControlHeaderValue = requestHeaders.CacheControl;
 119:   
 120:              // For unknown header, unknownheaderValues has zero items and unknownheaderValue is ""
 121:              IList<string> unknownheaderValues = headersDictionary["unknownheader"];
 122:              string unknownheaderValue = headersDictionary["unknownheader"].ToString();
 123:   
 124:              // For known header, knownheaderValues has 1 item and knownheaderValue is the value
 125:              IList<string> knownheaderValues = headersDictionary[HeaderNames.AcceptLanguage];
 126:              string knownheaderValue = headersDictionary[HeaderNames.AcceptLanguage].ToString();
 127:              #endregion
 128:   
 129:              // ASP.NET 4 - HttpContext.Request.UserAgent
 130:              #region snippet_Agent
 131:              string userAgent = headersDictionary[HeaderNames.UserAgent].ToString();
 132:              #endregion
 133:   
 134:              // ASP.NET 4 - HttpContext.Request.UrlReferrer
 135:              #region snippet_Referrer
 136:              string urlReferrer = headersDictionary[HeaderNames.Referer].ToString();
 137:              #endregion
 138:   
 139:              // ASP.NET 4 - HttpContext.Request.ContentType 
 140:              #region snippet_Type
 141:              // using Microsoft.Net.Http.Headers;
 142:   
 143:              MediaTypeHeaderValue mediaHeaderValue = requestHeaders.ContentType;
 144:              string contentType = mediaHeaderValue?.MediaType;   // ex. application/x-www-form-urlencoded
 145:              string contentMainType = mediaHeaderValue?.Type;    // ex. application
 146:              string contentSubType = mediaHeaderValue?.SubType;  // ex. x-www-form-urlencoded
 147:   
 148:              System.Text.Encoding requestEncoding = mediaHeaderValue?.Encoding;
 149:              #endregion
 150:   
 151:              // ASP.NET 4 - HttpContext.Request.Form 
 152:              #region snippet_Form
 153:              if (httpContext.Request.HasFormContentType)
 154:              {
 155:                  IFormCollection form;
 156:   
 157:                  form = httpContext.Request.Form; // sync
 158:                  // Or
 159:                  form = await httpContext.Request.ReadFormAsync(); // async
 160:   
 161:                  string firstName = form["firstname"];
 162:                  string lastName = form["lastname"];
 163:              }
 164:              #endregion
 165:   
 166:              // ----------
 167:              // See 
 168:              // http://stackoverflow.com/questions/31389781/read-body-twice-in-asp-net-5/
 169:   
 170:              // ASP.NET 4 - HttpContext.Request.InputStream
 171:              // Unlike reading the form, reading the raw body is not from a buffer.
 172:              // So you can only do this once per request.
 173:              // 
 174:              // If you need to read the body multiple times per request, see
 175:              // http://stackoverflow.com/questions/31389781/read-body-twice-in-asp-net-5/
 176:   
 177:              #region snippet_Input
 178:              string inputBody;
 179:              using (var reader = new System.IO.StreamReader(
 180:                  httpContext.Request.Body, System.Text.Encoding.UTF8))
 181:              {
 182:                  inputBody = reader.ReadToEnd();
 183:              }
 184:              #endregion
 185:   
 186:              // Use this middleware as a handler, so no call to 
 187:              // await _next.Invoke(aspnetCoreHttpContext);
 188:   
 189:              // ==================================================================
 190:              // Response
 191:   
 192:              // ASP.NET 4 - HttpContext.Response.Status  
 193:              // ASP.NET 4 - HttpContext.Response.StatusDescription (obsolete, removed from HTTP/2) 
 194:              #region snippet_Status
 195:              // using Microsoft.AspNetCore.Http;
 196:              httpContext.Response.StatusCode = StatusCodes.Status200OK;
 197:              #endregion
 198:   
 199:              // ASP.NET 4 - HttpContext.Response.ContentEncoding and HttpContext.Response.ContentType  
 200:              #region snippet_RespType
 201:              // using Microsoft.Net.Http.Headers;
 202:              var mediaType = new MediaTypeHeaderValue("application/json");
 203:              mediaType.Encoding = System.Text.Encoding.UTF8;
 204:              httpContext.Response.ContentType = mediaType.ToString();
 205:              #endregion
 206:   
 207:              // ASP.NET 4 - HttpContext.Response.ContentType only 
 208:              #region snippet_RespTypeOnly
 209:              httpContext.Response.ContentType = "text/html";
 210:              #endregion
 211:   
 212:              // ASP.NET 4 - HttpContext.Response.Output  
 213:              #region  snippet_Output
 214:              string responseContent = GetResponseContent();
 215:              await httpContext.Response.WriteAsync(responseContent);
 216:              #endregion
 217:          }
 218:   
 219:          #region snippet_SetHeaders
 220:          // using Microsoft.AspNet.Http.Headers;
 221:          // using Microsoft.Net.Http.Headers;
 222:   
 223:          private Task SetHeaders(object context)
 224:          {
 225:              var httpContext = (HttpContext)context;
 226:   
 227:              // Set header with single value
 228:              httpContext.Response.Headers["ResponseHeaderName"] = "headerValue";
 229:   
 230:              // Set header with multiple values
 231:              string[] responseHeaderValues = new string[] { "headerValue1", "headerValue1" };
 232:              httpContext.Response.Headers["ResponseHeaderName"] = responseHeaderValues;
 233:   
 234:              // Translating ASP.NET 4's HttpContext.Response.RedirectLocation  
 235:              httpContext.Response.Headers[HeaderNames.Location] = "http://www.example.com";
 236:              // Or
 237:              httpContext.Response.Redirect("http://www.example.com");
 238:   
 239:              // GetTypedHeaders extension method provides strongly typed access to many headers
 240:              var responseHeaders = httpContext.Response.GetTypedHeaders();
 241:   
 242:              // Translating ASP.NET 4's HttpContext.Response.CacheControl 
 243:              responseHeaders.CacheControl = new CacheControlHeaderValue
 244:              {
 245:                  MaxAge = new System.TimeSpan(365, 0, 0, 0)
 246:                  // Many more properties available 
 247:              };
 248:   
 249:              // If you use .Net 4.6+, Task.CompletedTask will be a bit faster
 250:              return Task.FromResult(0);
 251:          }
 252:          #endregion
 253:   
 254:          #region snippet_SetCookies
 255:          private Task SetCookies(object context)
 256:          {
 257:              var httpContext = (HttpContext)context;
 258:   
 259:              IResponseCookies responseCookies = httpContext.Response.Cookies;
 260:   
 261:              responseCookies.Append("cookie1name", "cookie1value");
 262:              responseCookies.Append("cookie2name", "cookie2value",
 263:                  new CookieOptions { Expires = System.DateTime.Now.AddDays(5), HttpOnly = true });
 264:   
 265:              // If you use .Net 4.6+, Task.CompletedTask will be a bit faster
 266:              return Task.FromResult(0); 
 267:          }
 268:          #endregion
 269:   
 270:          // You would normally use MVC to generate HTML like this.
 271:          private string GetResponseContent()
 272:          {
 273:              return @"
 274:  <!DOCTYPE html>
 275:  <html lang=""en"">
 276:  <head>
 277:      <title>index</title>
 278:  </head>
 279:  <body>
 280:  <form action=""form.context"" method=""post"">
 281:      <input type=""text"" name=""firstname"">
 282:      <input type=""text"" name=""lastname"">
 283:      <input type=""submit"" value=""Submit"">
 284:  </form> 
 285:  </body>
 286:  </html>
 287:  ";
 288:          }
 289:      }
 290:   
 291:      public static class HttpContextDemoMiddlewareExtensions
 292:      {
 293:          public static IApplicationBuilder UseHttpContextDemoMiddleware(this IApplicationBuilder builder)
 294:          {
 295:              return builder.UseMiddleware<HttpContextDemoMiddleware>();
 296:          }
 297:      }
 298:  }

[!WARNING] Read form values only if the content sub type is x-www-form-urlencoded or form-data.

HttpContext.Request.InputStream translates to:

[!code-csharpMain]

   1:  using Microsoft.AspNetCore.Builder;
   2:  using Microsoft.AspNetCore.Http;
   3:  using System.Collections.Generic;
   4:  using System.Threading.Tasks;
   5:  using Microsoft.Net.Http.Headers;
   6:  using Microsoft.AspNetCore.Http.Extensions;
   7:  using Microsoft.AspNetCore.Routing;
   8:   
   9:  namespace MyApp.Middleware
  10:  {
  11:      public class HttpContextDemoMiddleware
  12:      {
  13:          private readonly RequestDelegate _next;
  14:   
  15:          public HttpContextDemoMiddleware(RequestDelegate next)
  16:          {
  17:              _next = next;
  18:          }
  19:   
  20:          public async Task Invoke(HttpContext httpContext)
  21:          {
  22:              // OnStarting handlers have to be set early during request processing,
  23:              // even though they are used to create the response.
  24:   
  25:              // ----------------------
  26:              // ASP.NET 4 - HttpContext.Response.Headers  
  27:              // ASP.NET 4 - HttpContext.Response.Cookies  
  28:              // 
  29:              // Issue with all response headers is that they will not be sent 
  30:              // after anything has been written to the response body.
  31:              // To solve this, use OnStarting to set a callback that will be called 
  32:              // right before headers are sent. Set the headers in that callback.
  33:              //
  34:              // Setting a cookie results in a Set-Cookie response header.
  35:              // So use an OnStarting handler here as well.
  36:   
  37:              //>40
  38:              httpContext.Response.OnStarting(SetHeaders, state: httpContext);
  39:              httpContext.Response.OnStarting(SetCookies, state: httpContext);
  40:              //<40
  41:   
  42:              // ==================================================================
  43:              // Context
  44:   
  45:              // Unique request ID (no ASP.NET 4 counterpart)
  46:              #region snippet_Trace
  47:              string requestId = httpContext.TraceIdentifier;
  48:              #endregion
  49:   
  50:              // ASP.NET 4 - HttpContext.Items
  51:              #region snippet_Items
  52:              IDictionary<object, object> items = httpContext.Items;
  53:              #endregion
  54:   
  55:              // ==================================================================
  56:              // Request
  57:   
  58:              // ASP.NET 4 - HttpContext.Request.HttpMethod
  59:              #region snippet_Method
  60:              string httpMethod = httpContext.Request.Method;
  61:              #endregion
  62:   
  63:              // ----------
  64:   
  65:              // ASP.NET 4 - HttpContext.Request.QueryString
  66:              #region snippet_Query
  67:              IQueryCollection queryParameters = httpContext.Request.Query;
  68:   
  69:              // If no query parameter "key" used, values will have 0 items
  70:              // If single value used for a key (...?key=v1), values will have 1 item ("v1")
  71:              // If key has multiple values (...?key=v1&key=v2), values will have 2 items ("v1" and "v2")
  72:              IList<string> values = queryParameters["key"];
  73:   
  74:              // If no query parameter "key" used, value will be ""
  75:              // If single value used for a key (...?key=v1), value will be "v1"
  76:              // If key has multiple values (...?key=v1&key=v2), value will be "v1,v2"
  77:              string value = queryParameters["key"].ToString();
  78:              #endregion
  79:   
  80:              // ASP.NET 4 - HttpContext.Request.Url and HttpContext.Request.RawUrl
  81:              #region snippet_Url
  82:              // using Microsoft.AspNetCore.Http.Extensions;
  83:              var url = httpContext.Request.GetDisplayUrl();
  84:              #endregion
  85:   
  86:              // ASP.NET 4 - HttpContext.Request.IsSecureConnection
  87:              #region snippet_Secure
  88:              var isSecureConnection = httpContext.Request.IsHttps;
  89:              #endregion
  90:   
  91:              // ASP.NET 4 - HttpContext.Request.UserHostAddress
  92:              #region snippet_Host
  93:              var userHostAddress = httpContext.Connection.RemoteIpAddress?.ToString();
  94:              #endregion
  95:   
  96:              // ASP.NET 4 - HttpContext.Request.Cookies 
  97:              #region snippet_Cookies
  98:              IRequestCookieCollection cookies = httpContext.Request.Cookies;
  99:              string unknownCookieValue = cookies["unknownCookie"]; // will be null (no exception)
 100:              string knownCookieValue = cookies["cookie1name"];     // will be actual value
 101:              #endregion
 102:   
 103:              // ASP.NET 4 - HttpContext.Request.RequestContext.RouteData
 104:              // using Microsoft.AspNetCore.Routing;
 105:              #region snippet_Route
 106:              var routeValue = httpContext.GetRouteValue("key");
 107:              #endregion
 108:   
 109:              // ASP.NET 4 - HttpContext.Request.Headers
 110:              #region snippet_Headers
 111:              // using Microsoft.AspNetCore.Http.Headers;
 112:              // using Microsoft.Net.Http.Headers;
 113:   
 114:              IHeaderDictionary headersDictionary = httpContext.Request.Headers;
 115:   
 116:              // GetTypedHeaders extension method provides strongly typed access to many headers
 117:              var requestHeaders = httpContext.Request.GetTypedHeaders();
 118:              CacheControlHeaderValue cacheControlHeaderValue = requestHeaders.CacheControl;
 119:   
 120:              // For unknown header, unknownheaderValues has zero items and unknownheaderValue is ""
 121:              IList<string> unknownheaderValues = headersDictionary["unknownheader"];
 122:              string unknownheaderValue = headersDictionary["unknownheader"].ToString();
 123:   
 124:              // For known header, knownheaderValues has 1 item and knownheaderValue is the value
 125:              IList<string> knownheaderValues = headersDictionary[HeaderNames.AcceptLanguage];
 126:              string knownheaderValue = headersDictionary[HeaderNames.AcceptLanguage].ToString();
 127:              #endregion
 128:   
 129:              // ASP.NET 4 - HttpContext.Request.UserAgent
 130:              #region snippet_Agent
 131:              string userAgent = headersDictionary[HeaderNames.UserAgent].ToString();
 132:              #endregion
 133:   
 134:              // ASP.NET 4 - HttpContext.Request.UrlReferrer
 135:              #region snippet_Referrer
 136:              string urlReferrer = headersDictionary[HeaderNames.Referer].ToString();
 137:              #endregion
 138:   
 139:              // ASP.NET 4 - HttpContext.Request.ContentType 
 140:              #region snippet_Type
 141:              // using Microsoft.Net.Http.Headers;
 142:   
 143:              MediaTypeHeaderValue mediaHeaderValue = requestHeaders.ContentType;
 144:              string contentType = mediaHeaderValue?.MediaType;   // ex. application/x-www-form-urlencoded
 145:              string contentMainType = mediaHeaderValue?.Type;    // ex. application
 146:              string contentSubType = mediaHeaderValue?.SubType;  // ex. x-www-form-urlencoded
 147:   
 148:              System.Text.Encoding requestEncoding = mediaHeaderValue?.Encoding;
 149:              #endregion
 150:   
 151:              // ASP.NET 4 - HttpContext.Request.Form 
 152:              #region snippet_Form
 153:              if (httpContext.Request.HasFormContentType)
 154:              {
 155:                  IFormCollection form;
 156:   
 157:                  form = httpContext.Request.Form; // sync
 158:                  // Or
 159:                  form = await httpContext.Request.ReadFormAsync(); // async
 160:   
 161:                  string firstName = form["firstname"];
 162:                  string lastName = form["lastname"];
 163:              }
 164:              #endregion
 165:   
 166:              // ----------
 167:              // See 
 168:              // http://stackoverflow.com/questions/31389781/read-body-twice-in-asp-net-5/
 169:   
 170:              // ASP.NET 4 - HttpContext.Request.InputStream
 171:              // Unlike reading the form, reading the raw body is not from a buffer.
 172:              // So you can only do this once per request.
 173:              // 
 174:              // If you need to read the body multiple times per request, see
 175:              // http://stackoverflow.com/questions/31389781/read-body-twice-in-asp-net-5/
 176:   
 177:              #region snippet_Input
 178:              string inputBody;
 179:              using (var reader = new System.IO.StreamReader(
 180:                  httpContext.Request.Body, System.Text.Encoding.UTF8))
 181:              {
 182:                  inputBody = reader.ReadToEnd();
 183:              }
 184:              #endregion
 185:   
 186:              // Use this middleware as a handler, so no call to 
 187:              // await _next.Invoke(aspnetCoreHttpContext);
 188:   
 189:              // ==================================================================
 190:              // Response
 191:   
 192:              // ASP.NET 4 - HttpContext.Response.Status  
 193:              // ASP.NET 4 - HttpContext.Response.StatusDescription (obsolete, removed from HTTP/2) 
 194:              #region snippet_Status
 195:              // using Microsoft.AspNetCore.Http;
 196:              httpContext.Response.StatusCode = StatusCodes.Status200OK;
 197:              #endregion
 198:   
 199:              // ASP.NET 4 - HttpContext.Response.ContentEncoding and HttpContext.Response.ContentType  
 200:              #region snippet_RespType
 201:              // using Microsoft.Net.Http.Headers;
 202:              var mediaType = new MediaTypeHeaderValue("application/json");
 203:              mediaType.Encoding = System.Text.Encoding.UTF8;
 204:              httpContext.Response.ContentType = mediaType.ToString();
 205:              #endregion
 206:   
 207:              // ASP.NET 4 - HttpContext.Response.ContentType only 
 208:              #region snippet_RespTypeOnly
 209:              httpContext.Response.ContentType = "text/html";
 210:              #endregion
 211:   
 212:              // ASP.NET 4 - HttpContext.Response.Output  
 213:              #region  snippet_Output
 214:              string responseContent = GetResponseContent();
 215:              await httpContext.Response.WriteAsync(responseContent);
 216:              #endregion
 217:          }
 218:   
 219:          #region snippet_SetHeaders
 220:          // using Microsoft.AspNet.Http.Headers;
 221:          // using Microsoft.Net.Http.Headers;
 222:   
 223:          private Task SetHeaders(object context)
 224:          {
 225:              var httpContext = (HttpContext)context;
 226:   
 227:              // Set header with single value
 228:              httpContext.Response.Headers["ResponseHeaderName"] = "headerValue";
 229:   
 230:              // Set header with multiple values
 231:              string[] responseHeaderValues = new string[] { "headerValue1", "headerValue1" };
 232:              httpContext.Response.Headers["ResponseHeaderName"] = responseHeaderValues;
 233:   
 234:              // Translating ASP.NET 4's HttpContext.Response.RedirectLocation  
 235:              httpContext.Response.Headers[HeaderNames.Location] = "http://www.example.com";
 236:              // Or
 237:              httpContext.Response.Redirect("http://www.example.com");
 238:   
 239:              // GetTypedHeaders extension method provides strongly typed access to many headers
 240:              var responseHeaders = httpContext.Response.GetTypedHeaders();
 241:   
 242:              // Translating ASP.NET 4's HttpContext.Response.CacheControl 
 243:              responseHeaders.CacheControl = new CacheControlHeaderValue
 244:              {
 245:                  MaxAge = new System.TimeSpan(365, 0, 0, 0)
 246:                  // Many more properties available 
 247:              };
 248:   
 249:              // If you use .Net 4.6+, Task.CompletedTask will be a bit faster
 250:              return Task.FromResult(0);
 251:          }
 252:          #endregion
 253:   
 254:          #region snippet_SetCookies
 255:          private Task SetCookies(object context)
 256:          {
 257:              var httpContext = (HttpContext)context;
 258:   
 259:              IResponseCookies responseCookies = httpContext.Response.Cookies;
 260:   
 261:              responseCookies.Append("cookie1name", "cookie1value");
 262:              responseCookies.Append("cookie2name", "cookie2value",
 263:                  new CookieOptions { Expires = System.DateTime.Now.AddDays(5), HttpOnly = true });
 264:   
 265:              // If you use .Net 4.6+, Task.CompletedTask will be a bit faster
 266:              return Task.FromResult(0); 
 267:          }
 268:          #endregion
 269:   
 270:          // You would normally use MVC to generate HTML like this.
 271:          private string GetResponseContent()
 272:          {
 273:              return @"
 274:  <!DOCTYPE html>
 275:  <html lang=""en"">
 276:  <head>
 277:      <title>index</title>
 278:  </head>
 279:  <body>
 280:  <form action=""form.context"" method=""post"">
 281:      <input type=""text"" name=""firstname"">
 282:      <input type=""text"" name=""lastname"">
 283:      <input type=""submit"" value=""Submit"">
 284:  </form> 
 285:  </body>
 286:  </html>
 287:  ";
 288:          }
 289:      }
 290:   
 291:      public static class HttpContextDemoMiddlewareExtensions
 292:      {
 293:          public static IApplicationBuilder UseHttpContextDemoMiddleware(this IApplicationBuilder builder)
 294:          {
 295:              return builder.UseMiddleware<HttpContextDemoMiddleware>();
 296:          }
 297:      }
 298:  }

[!WARNING] Use this code only in a handler type middleware, at the end of a pipeline.

You can read the raw body as shown above only once per request. Middleware trying to read the body after the first read will read an empty body.

This does not apply to reading a form as shown earlier, because that is done from a buffer.

HttpContext.Response

HttpContext.Response.Status and HttpContext.Response.StatusDescription translate to:

[!code-csharpMain]

   1:  using Microsoft.AspNetCore.Builder;
   2:  using Microsoft.AspNetCore.Http;
   3:  using System.Collections.Generic;
   4:  using System.Threading.Tasks;
   5:  using Microsoft.Net.Http.Headers;
   6:  using Microsoft.AspNetCore.Http.Extensions;
   7:  using Microsoft.AspNetCore.Routing;
   8:   
   9:  namespace MyApp.Middleware
  10:  {
  11:      public class HttpContextDemoMiddleware
  12:      {
  13:          private readonly RequestDelegate _next;
  14:   
  15:          public HttpContextDemoMiddleware(RequestDelegate next)
  16:          {
  17:              _next = next;
  18:          }
  19:   
  20:          public async Task Invoke(HttpContext httpContext)
  21:          {
  22:              // OnStarting handlers have to be set early during request processing,
  23:              // even though they are used to create the response.
  24:   
  25:              // ----------------------
  26:              // ASP.NET 4 - HttpContext.Response.Headers  
  27:              // ASP.NET 4 - HttpContext.Response.Cookies  
  28:              // 
  29:              // Issue with all response headers is that they will not be sent 
  30:              // after anything has been written to the response body.
  31:              // To solve this, use OnStarting to set a callback that will be called 
  32:              // right before headers are sent. Set the headers in that callback.
  33:              //
  34:              // Setting a cookie results in a Set-Cookie response header.
  35:              // So use an OnStarting handler here as well.
  36:   
  37:              //>40
  38:              httpContext.Response.OnStarting(SetHeaders, state: httpContext);
  39:              httpContext.Response.OnStarting(SetCookies, state: httpContext);
  40:              //<40
  41:   
  42:              // ==================================================================
  43:              // Context
  44:   
  45:              // Unique request ID (no ASP.NET 4 counterpart)
  46:              #region snippet_Trace
  47:              string requestId = httpContext.TraceIdentifier;
  48:              #endregion
  49:   
  50:              // ASP.NET 4 - HttpContext.Items
  51:              #region snippet_Items
  52:              IDictionary<object, object> items = httpContext.Items;
  53:              #endregion
  54:   
  55:              // ==================================================================
  56:              // Request
  57:   
  58:              // ASP.NET 4 - HttpContext.Request.HttpMethod
  59:              #region snippet_Method
  60:              string httpMethod = httpContext.Request.Method;
  61:              #endregion
  62:   
  63:              // ----------
  64:   
  65:              // ASP.NET 4 - HttpContext.Request.QueryString
  66:              #region snippet_Query
  67:              IQueryCollection queryParameters = httpContext.Request.Query;
  68:   
  69:              // If no query parameter "key" used, values will have 0 items
  70:              // If single value used for a key (...?key=v1), values will have 1 item ("v1")
  71:              // If key has multiple values (...?key=v1&key=v2), values will have 2 items ("v1" and "v2")
  72:              IList<string> values = queryParameters["key"];
  73:   
  74:              // If no query parameter "key" used, value will be ""
  75:              // If single value used for a key (...?key=v1), value will be "v1"
  76:              // If key has multiple values (...?key=v1&key=v2), value will be "v1,v2"
  77:              string value = queryParameters["key"].ToString();
  78:              #endregion
  79:   
  80:              // ASP.NET 4 - HttpContext.Request.Url and HttpContext.Request.RawUrl
  81:              #region snippet_Url
  82:              // using Microsoft.AspNetCore.Http.Extensions;
  83:              var url = httpContext.Request.GetDisplayUrl();
  84:              #endregion
  85:   
  86:              // ASP.NET 4 - HttpContext.Request.IsSecureConnection
  87:              #region snippet_Secure
  88:              var isSecureConnection = httpContext.Request.IsHttps;
  89:              #endregion
  90:   
  91:              // ASP.NET 4 - HttpContext.Request.UserHostAddress
  92:              #region snippet_Host
  93:              var userHostAddress = httpContext.Connection.RemoteIpAddress?.ToString();
  94:              #endregion
  95:   
  96:              // ASP.NET 4 - HttpContext.Request.Cookies 
  97:              #region snippet_Cookies
  98:              IRequestCookieCollection cookies = httpContext.Request.Cookies;
  99:              string unknownCookieValue = cookies["unknownCookie"]; // will be null (no exception)
 100:              string knownCookieValue = cookies["cookie1name"];     // will be actual value
 101:              #endregion
 102:   
 103:              // ASP.NET 4 - HttpContext.Request.RequestContext.RouteData
 104:              // using Microsoft.AspNetCore.Routing;
 105:              #region snippet_Route
 106:              var routeValue = httpContext.GetRouteValue("key");
 107:              #endregion
 108:   
 109:              // ASP.NET 4 - HttpContext.Request.Headers
 110:              #region snippet_Headers
 111:              // using Microsoft.AspNetCore.Http.Headers;
 112:              // using Microsoft.Net.Http.Headers;
 113:   
 114:              IHeaderDictionary headersDictionary = httpContext.Request.Headers;
 115:   
 116:              // GetTypedHeaders extension method provides strongly typed access to many headers
 117:              var requestHeaders = httpContext.Request.GetTypedHeaders();
 118:              CacheControlHeaderValue cacheControlHeaderValue = requestHeaders.CacheControl;
 119:   
 120:              // For unknown header, unknownheaderValues has zero items and unknownheaderValue is ""
 121:              IList<string> unknownheaderValues = headersDictionary["unknownheader"];
 122:              string unknownheaderValue = headersDictionary["unknownheader"].ToString();
 123:   
 124:              // For known header, knownheaderValues has 1 item and knownheaderValue is the value
 125:              IList<string> knownheaderValues = headersDictionary[HeaderNames.AcceptLanguage];
 126:              string knownheaderValue = headersDictionary[HeaderNames.AcceptLanguage].ToString();
 127:              #endregion
 128:   
 129:              // ASP.NET 4 - HttpContext.Request.UserAgent
 130:              #region snippet_Agent
 131:              string userAgent = headersDictionary[HeaderNames.UserAgent].ToString();
 132:              #endregion
 133:   
 134:              // ASP.NET 4 - HttpContext.Request.UrlReferrer
 135:              #region snippet_Referrer
 136:              string urlReferrer = headersDictionary[HeaderNames.Referer].ToString();
 137:              #endregion
 138:   
 139:              // ASP.NET 4 - HttpContext.Request.ContentType 
 140:              #region snippet_Type
 141:              // using Microsoft.Net.Http.Headers;
 142:   
 143:              MediaTypeHeaderValue mediaHeaderValue = requestHeaders.ContentType;
 144:              string contentType = mediaHeaderValue?.MediaType;   // ex. application/x-www-form-urlencoded
 145:              string contentMainType = mediaHeaderValue?.Type;    // ex. application
 146:              string contentSubType = mediaHeaderValue?.SubType;  // ex. x-www-form-urlencoded
 147:   
 148:              System.Text.Encoding requestEncoding = mediaHeaderValue?.Encoding;
 149:              #endregion
 150:   
 151:              // ASP.NET 4 - HttpContext.Request.Form 
 152:              #region snippet_Form
 153:              if (httpContext.Request.HasFormContentType)
 154:              {
 155:                  IFormCollection form;
 156:   
 157:                  form = httpContext.Request.Form; // sync
 158:                  // Or
 159:                  form = await httpContext.Request.ReadFormAsync(); // async
 160:   
 161:                  string firstName = form["firstname"];
 162:                  string lastName = form["lastname"];
 163:              }
 164:              #endregion
 165:   
 166:              // ----------
 167:              // See 
 168:              // http://stackoverflow.com/questions/31389781/read-body-twice-in-asp-net-5/
 169:   
 170:              // ASP.NET 4 - HttpContext.Request.InputStream
 171:              // Unlike reading the form, reading the raw body is not from a buffer.
 172:              // So you can only do this once per request.
 173:              // 
 174:              // If you need to read the body multiple times per request, see
 175:              // http://stackoverflow.com/questions/31389781/read-body-twice-in-asp-net-5/
 176:   
 177:              #region snippet_Input
 178:              string inputBody;
 179:              using (var reader = new System.IO.StreamReader(
 180:                  httpContext.Request.Body, System.Text.Encoding.UTF8))
 181:              {
 182:                  inputBody = reader.ReadToEnd();
 183:              }
 184:              #endregion
 185:   
 186:              // Use this middleware as a handler, so no call to 
 187:              // await _next.Invoke(aspnetCoreHttpContext);
 188:   
 189:              // ==================================================================
 190:              // Response
 191:   
 192:              // ASP.NET 4 - HttpContext.Response.Status  
 193:              // ASP.NET 4 - HttpContext.Response.StatusDescription (obsolete, removed from HTTP/2) 
 194:              #region snippet_Status
 195:              // using Microsoft.AspNetCore.Http;
 196:              httpContext.Response.StatusCode = StatusCodes.Status200OK;
 197:              #endregion
 198:   
 199:              // ASP.NET 4 - HttpContext.Response.ContentEncoding and HttpContext.Response.ContentType  
 200:              #region snippet_RespType
 201:              // using Microsoft.Net.Http.Headers;
 202:              var mediaType = new MediaTypeHeaderValue("application/json");
 203:              mediaType.Encoding = System.Text.Encoding.UTF8;
 204:              httpContext.Response.ContentType = mediaType.ToString();
 205:              #endregion
 206:   
 207:              // ASP.NET 4 - HttpContext.Response.ContentType only 
 208:              #region snippet_RespTypeOnly
 209:              httpContext.Response.ContentType = "text/html";
 210:              #endregion
 211:   
 212:              // ASP.NET 4 - HttpContext.Response.Output  
 213:              #region  snippet_Output
 214:              string responseContent = GetResponseContent();
 215:              await httpContext.Response.WriteAsync(responseContent);
 216:              #endregion
 217:          }
 218:   
 219:          #region snippet_SetHeaders
 220:          // using Microsoft.AspNet.Http.Headers;
 221:          // using Microsoft.Net.Http.Headers;
 222:   
 223:          private Task SetHeaders(object context)
 224:          {
 225:              var httpContext = (HttpContext)context;
 226:   
 227:              // Set header with single value
 228:              httpContext.Response.Headers["ResponseHeaderName"] = "headerValue";
 229:   
 230:              // Set header with multiple values
 231:              string[] responseHeaderValues = new string[] { "headerValue1", "headerValue1" };
 232:              httpContext.Response.Headers["ResponseHeaderName"] = responseHeaderValues;
 233:   
 234:              // Translating ASP.NET 4's HttpContext.Response.RedirectLocation  
 235:              httpContext.Response.Headers[HeaderNames.Location] = "http://www.example.com";
 236:              // Or
 237:              httpContext.Response.Redirect("http://www.example.com");
 238:   
 239:              // GetTypedHeaders extension method provides strongly typed access to many headers
 240:              var responseHeaders = httpContext.Response.GetTypedHeaders();
 241:   
 242:              // Translating ASP.NET 4's HttpContext.Response.CacheControl 
 243:              responseHeaders.CacheControl = new CacheControlHeaderValue
 244:              {
 245:                  MaxAge = new System.TimeSpan(365, 0, 0, 0)
 246:                  // Many more properties available 
 247:              };
 248:   
 249:              // If you use .Net 4.6+, Task.CompletedTask will be a bit faster
 250:              return Task.FromResult(0);
 251:          }
 252:          #endregion
 253:   
 254:          #region snippet_SetCookies
 255:          private Task SetCookies(object context)
 256:          {
 257:              var httpContext = (HttpContext)context;
 258:   
 259:              IResponseCookies responseCookies = httpContext.Response.Cookies;
 260:   
 261:              responseCookies.Append("cookie1name", "cookie1value");
 262:              responseCookies.Append("cookie2name", "cookie2value",
 263:                  new CookieOptions { Expires = System.DateTime.Now.AddDays(5), HttpOnly = true });
 264:   
 265:              // If you use .Net 4.6+, Task.CompletedTask will be a bit faster
 266:              return Task.FromResult(0); 
 267:          }
 268:          #endregion
 269:   
 270:          // You would normally use MVC to generate HTML like this.
 271:          private string GetResponseContent()
 272:          {
 273:              return @"
 274:  <!DOCTYPE html>
 275:  <html lang=""en"">
 276:  <head>
 277:      <title>index</title>
 278:  </head>
 279:  <body>
 280:  <form action=""form.context"" method=""post"">
 281:      <input type=""text"" name=""firstname"">
 282:      <input type=""text"" name=""lastname"">
 283:      <input type=""submit"" value=""Submit"">
 284:  </form> 
 285:  </body>
 286:  </html>
 287:  ";
 288:          }
 289:      }
 290:   
 291:      public static class HttpContextDemoMiddlewareExtensions
 292:      {
 293:          public static IApplicationBuilder UseHttpContextDemoMiddleware(this IApplicationBuilder builder)
 294:          {
 295:              return builder.UseMiddleware<HttpContextDemoMiddleware>();
 296:          }
 297:      }
 298:  }

HttpContext.Response.ContentEncoding and HttpContext.Response.ContentType translate to:

[!code-csharpMain]

   1:  using Microsoft.AspNetCore.Builder;
   2:  using Microsoft.AspNetCore.Http;
   3:  using System.Collections.Generic;
   4:  using System.Threading.Tasks;
   5:  using Microsoft.Net.Http.Headers;
   6:  using Microsoft.AspNetCore.Http.Extensions;
   7:  using Microsoft.AspNetCore.Routing;
   8:   
   9:  namespace MyApp.Middleware
  10:  {
  11:      public class HttpContextDemoMiddleware
  12:      {
  13:          private readonly RequestDelegate _next;
  14:   
  15:          public HttpContextDemoMiddleware(RequestDelegate next)
  16:          {
  17:              _next = next;
  18:          }
  19:   
  20:          public async Task Invoke(HttpContext httpContext)
  21:          {
  22:              // OnStarting handlers have to be set early during request processing,
  23:              // even though they are used to create the response.
  24:   
  25:              // ----------------------
  26:              // ASP.NET 4 - HttpContext.Response.Headers  
  27:              // ASP.NET 4 - HttpContext.Response.Cookies  
  28:              // 
  29:              // Issue with all response headers is that they will not be sent 
  30:              // after anything has been written to the response body.
  31:              // To solve this, use OnStarting to set a callback that will be called 
  32:              // right before headers are sent. Set the headers in that callback.
  33:              //
  34:              // Setting a cookie results in a Set-Cookie response header.
  35:              // So use an OnStarting handler here as well.
  36:   
  37:              //>40
  38:              httpContext.Response.OnStarting(SetHeaders, state: httpContext);
  39:              httpContext.Response.OnStarting(SetCookies, state: httpContext);
  40:              //<40
  41:   
  42:              // ==================================================================
  43:              // Context
  44:   
  45:              // Unique request ID (no ASP.NET 4 counterpart)
  46:              #region snippet_Trace
  47:              string requestId = httpContext.TraceIdentifier;
  48:              #endregion
  49:   
  50:              // ASP.NET 4 - HttpContext.Items
  51:              #region snippet_Items
  52:              IDictionary<object, object> items = httpContext.Items;
  53:              #endregion
  54:   
  55:              // ==================================================================
  56:              // Request
  57:   
  58:              // ASP.NET 4 - HttpContext.Request.HttpMethod
  59:              #region snippet_Method
  60:              string httpMethod = httpContext.Request.Method;
  61:              #endregion
  62:   
  63:              // ----------
  64:   
  65:              // ASP.NET 4 - HttpContext.Request.QueryString
  66:              #region snippet_Query
  67:              IQueryCollection queryParameters = httpContext.Request.Query;
  68:   
  69:              // If no query parameter "key" used, values will have 0 items
  70:              // If single value used for a key (...?key=v1), values will have 1 item ("v1")
  71:              // If key has multiple values (...?key=v1&key=v2), values will have 2 items ("v1" and "v2")
  72:              IList<string> values = queryParameters["key"];
  73:   
  74:              // If no query parameter "key" used, value will be ""
  75:              // If single value used for a key (...?key=v1), value will be "v1"
  76:              // If key has multiple values (...?key=v1&key=v2), value will be "v1,v2"
  77:              string value = queryParameters["key"].ToString();
  78:              #endregion
  79:   
  80:              // ASP.NET 4 - HttpContext.Request.Url and HttpContext.Request.RawUrl
  81:              #region snippet_Url
  82:              // using Microsoft.AspNetCore.Http.Extensions;
  83:              var url = httpContext.Request.GetDisplayUrl();
  84:              #endregion
  85:   
  86:              // ASP.NET 4 - HttpContext.Request.IsSecureConnection
  87:              #region snippet_Secure
  88:              var isSecureConnection = httpContext.Request.IsHttps;
  89:              #endregion
  90:   
  91:              // ASP.NET 4 - HttpContext.Request.UserHostAddress
  92:              #region snippet_Host
  93:              var userHostAddress = httpContext.Connection.RemoteIpAddress?.ToString();
  94:              #endregion
  95:   
  96:              // ASP.NET 4 - HttpContext.Request.Cookies 
  97:              #region snippet_Cookies
  98:              IRequestCookieCollection cookies = httpContext.Request.Cookies;
  99:              string unknownCookieValue = cookies["unknownCookie"]; // will be null (no exception)
 100:              string knownCookieValue = cookies["cookie1name"];     // will be actual value
 101:              #endregion
 102:   
 103:              // ASP.NET 4 - HttpContext.Request.RequestContext.RouteData
 104:              // using Microsoft.AspNetCore.Routing;
 105:              #region snippet_Route
 106:              var routeValue = httpContext.GetRouteValue("key");
 107:              #endregion
 108:   
 109:              // ASP.NET 4 - HttpContext.Request.Headers
 110:              #region snippet_Headers
 111:              // using Microsoft.AspNetCore.Http.Headers;
 112:              // using Microsoft.Net.Http.Headers;
 113:   
 114:              IHeaderDictionary headersDictionary = httpContext.Request.Headers;
 115:   
 116:              // GetTypedHeaders extension method provides strongly typed access to many headers
 117:              var requestHeaders = httpContext.Request.GetTypedHeaders();
 118:              CacheControlHeaderValue cacheControlHeaderValue = requestHeaders.CacheControl;
 119:   
 120:              // For unknown header, unknownheaderValues has zero items and unknownheaderValue is ""
 121:              IList<string> unknownheaderValues = headersDictionary["unknownheader"];
 122:              string unknownheaderValue = headersDictionary["unknownheader"].ToString();
 123:   
 124:              // For known header, knownheaderValues has 1 item and knownheaderValue is the value
 125:              IList<string> knownheaderValues = headersDictionary[HeaderNames.AcceptLanguage];
 126:              string knownheaderValue = headersDictionary[HeaderNames.AcceptLanguage].ToString();
 127:              #endregion
 128:   
 129:              // ASP.NET 4 - HttpContext.Request.UserAgent
 130:              #region snippet_Agent
 131:              string userAgent = headersDictionary[HeaderNames.UserAgent].ToString();
 132:              #endregion
 133:   
 134:              // ASP.NET 4 - HttpContext.Request.UrlReferrer
 135:              #region snippet_Referrer
 136:              string urlReferrer = headersDictionary[HeaderNames.Referer].ToString();
 137:              #endregion
 138:   
 139:              // ASP.NET 4 - HttpContext.Request.ContentType 
 140:              #region snippet_Type
 141:              // using Microsoft.Net.Http.Headers;
 142:   
 143:              MediaTypeHeaderValue mediaHeaderValue = requestHeaders.ContentType;
 144:              string contentType = mediaHeaderValue?.MediaType;   // ex. application/x-www-form-urlencoded
 145:              string contentMainType = mediaHeaderValue?.Type;    // ex. application
 146:              string contentSubType = mediaHeaderValue?.SubType;  // ex. x-www-form-urlencoded
 147:   
 148:              System.Text.Encoding requestEncoding = mediaHeaderValue?.Encoding;
 149:              #endregion
 150:   
 151:              // ASP.NET 4 - HttpContext.Request.Form 
 152:              #region snippet_Form
 153:              if (httpContext.Request.HasFormContentType)
 154:              {
 155:                  IFormCollection form;
 156:   
 157:                  form = httpContext.Request.Form; // sync
 158:                  // Or
 159:                  form = await httpContext.Request.ReadFormAsync(); // async
 160:   
 161:                  string firstName = form["firstname"];
 162:                  string lastName = form["lastname"];
 163:              }
 164:              #endregion
 165:   
 166:              // ----------
 167:              // See 
 168:              // http://stackoverflow.com/questions/31389781/read-body-twice-in-asp-net-5/
 169:   
 170:              // ASP.NET 4 - HttpContext.Request.InputStream
 171:              // Unlike reading the form, reading the raw body is not from a buffer.
 172:              // So you can only do this once per request.
 173:              // 
 174:              // If you need to read the body multiple times per request, see
 175:              // http://stackoverflow.com/questions/31389781/read-body-twice-in-asp-net-5/
 176:   
 177:              #region snippet_Input
 178:              string inputBody;
 179:              using (var reader = new System.IO.StreamReader(
 180:                  httpContext.Request.Body, System.Text.Encoding.UTF8))
 181:              {
 182:                  inputBody = reader.ReadToEnd();
 183:              }
 184:              #endregion
 185:   
 186:              // Use this middleware as a handler, so no call to 
 187:              // await _next.Invoke(aspnetCoreHttpContext);
 188:   
 189:              // ==================================================================
 190:              // Response
 191:   
 192:              // ASP.NET 4 - HttpContext.Response.Status  
 193:              // ASP.NET 4 - HttpContext.Response.StatusDescription (obsolete, removed from HTTP/2) 
 194:              #region snippet_Status
 195:              // using Microsoft.AspNetCore.Http;
 196:              httpContext.Response.StatusCode = StatusCodes.Status200OK;
 197:              #endregion
 198:   
 199:              // ASP.NET 4 - HttpContext.Response.ContentEncoding and HttpContext.Response.ContentType  
 200:              #region snippet_RespType
 201:              // using Microsoft.Net.Http.Headers;
 202:              var mediaType = new MediaTypeHeaderValue("application/json");
 203:              mediaType.Encoding = System.Text.Encoding.UTF8;
 204:              httpContext.Response.ContentType = mediaType.ToString();
 205:              #endregion
 206:   
 207:              // ASP.NET 4 - HttpContext.Response.ContentType only 
 208:              #region snippet_RespTypeOnly
 209:              httpContext.Response.ContentType = "text/html";
 210:              #endregion
 211:   
 212:              // ASP.NET 4 - HttpContext.Response.Output  
 213:              #region  snippet_Output
 214:              string responseContent = GetResponseContent();
 215:              await httpContext.Response.WriteAsync(responseContent);
 216:              #endregion
 217:          }
 218:   
 219:          #region snippet_SetHeaders
 220:          // using Microsoft.AspNet.Http.Headers;
 221:          // using Microsoft.Net.Http.Headers;
 222:   
 223:          private Task SetHeaders(object context)
 224:          {
 225:              var httpContext = (HttpContext)context;
 226:   
 227:              // Set header with single value
 228:              httpContext.Response.Headers["ResponseHeaderName"] = "headerValue";
 229:   
 230:              // Set header with multiple values
 231:              string[] responseHeaderValues = new string[] { "headerValue1", "headerValue1" };
 232:              httpContext.Response.Headers["ResponseHeaderName"] = responseHeaderValues;
 233:   
 234:              // Translating ASP.NET 4's HttpContext.Response.RedirectLocation  
 235:              httpContext.Response.Headers[HeaderNames.Location] = "http://www.example.com";
 236:              // Or
 237:              httpContext.Response.Redirect("http://www.example.com");
 238:   
 239:              // GetTypedHeaders extension method provides strongly typed access to many headers
 240:              var responseHeaders = httpContext.Response.GetTypedHeaders();
 241:   
 242:              // Translating ASP.NET 4's HttpContext.Response.CacheControl 
 243:              responseHeaders.CacheControl = new CacheControlHeaderValue
 244:              {
 245:                  MaxAge = new System.TimeSpan(365, 0, 0, 0)
 246:                  // Many more properties available 
 247:              };
 248:   
 249:              // If you use .Net 4.6+, Task.CompletedTask will be a bit faster
 250:              return Task.FromResult(0);
 251:          }
 252:          #endregion
 253:   
 254:          #region snippet_SetCookies
 255:          private Task SetCookies(object context)
 256:          {
 257:              var httpContext = (HttpContext)context;
 258:   
 259:              IResponseCookies responseCookies = httpContext.Response.Cookies;
 260:   
 261:              responseCookies.Append("cookie1name", "cookie1value");
 262:              responseCookies.Append("cookie2name", "cookie2value",
 263:                  new CookieOptions { Expires = System.DateTime.Now.AddDays(5), HttpOnly = true });
 264:   
 265:              // If you use .Net 4.6+, Task.CompletedTask will be a bit faster
 266:              return Task.FromResult(0); 
 267:          }
 268:          #endregion
 269:   
 270:          // You would normally use MVC to generate HTML like this.
 271:          private string GetResponseContent()
 272:          {
 273:              return @"
 274:  <!DOCTYPE html>
 275:  <html lang=""en"">
 276:  <head>
 277:      <title>index</title>
 278:  </head>
 279:  <body>
 280:  <form action=""form.context"" method=""post"">
 281:      <input type=""text"" name=""firstname"">
 282:      <input type=""text"" name=""lastname"">
 283:      <input type=""submit"" value=""Submit"">
 284:  </form> 
 285:  </body>
 286:  </html>
 287:  ";
 288:          }
 289:      }
 290:   
 291:      public static class HttpContextDemoMiddlewareExtensions
 292:      {
 293:          public static IApplicationBuilder UseHttpContextDemoMiddleware(this IApplicationBuilder builder)
 294:          {
 295:              return builder.UseMiddleware<HttpContextDemoMiddleware>();
 296:          }
 297:      }
 298:  }

HttpContext.Response.ContentType on its own also translates to:

[!code-csharpMain]

   1:  using Microsoft.AspNetCore.Builder;
   2:  using Microsoft.AspNetCore.Http;
   3:  using System.Collections.Generic;
   4:  using System.Threading.Tasks;
   5:  using Microsoft.Net.Http.Headers;
   6:  using Microsoft.AspNetCore.Http.Extensions;
   7:  using Microsoft.AspNetCore.Routing;
   8:   
   9:  namespace MyApp.Middleware
  10:  {
  11:      public class HttpContextDemoMiddleware
  12:      {
  13:          private readonly RequestDelegate _next;
  14:   
  15:          public HttpContextDemoMiddleware(RequestDelegate next)
  16:          {
  17:              _next = next;
  18:          }
  19:   
  20:          public async Task Invoke(HttpContext httpContext)
  21:          {
  22:              // OnStarting handlers have to be set early during request processing,
  23:              // even though they are used to create the response.
  24:   
  25:              // ----------------------
  26:              // ASP.NET 4 - HttpContext.Response.Headers  
  27:              // ASP.NET 4 - HttpContext.Response.Cookies  
  28:              // 
  29:              // Issue with all response headers is that they will not be sent 
  30:              // after anything has been written to the response body.
  31:              // To solve this, use OnStarting to set a callback that will be called 
  32:              // right before headers are sent. Set the headers in that callback.
  33:              //
  34:              // Setting a cookie results in a Set-Cookie response header.
  35:              // So use an OnStarting handler here as well.
  36:   
  37:              //>40
  38:              httpContext.Response.OnStarting(SetHeaders, state: httpContext);
  39:              httpContext.Response.OnStarting(SetCookies, state: httpContext);
  40:              //<40
  41:   
  42:              // ==================================================================
  43:              // Context
  44:   
  45:              // Unique request ID (no ASP.NET 4 counterpart)
  46:              #region snippet_Trace
  47:              string requestId = httpContext.TraceIdentifier;
  48:              #endregion
  49:   
  50:              // ASP.NET 4 - HttpContext.Items
  51:              #region snippet_Items
  52:              IDictionary<object, object> items = httpContext.Items;
  53:              #endregion
  54:   
  55:              // ==================================================================
  56:              // Request
  57:   
  58:              // ASP.NET 4 - HttpContext.Request.HttpMethod
  59:              #region snippet_Method
  60:              string httpMethod = httpContext.Request.Method;
  61:              #endregion
  62:   
  63:              // ----------
  64:   
  65:              // ASP.NET 4 - HttpContext.Request.QueryString
  66:              #region snippet_Query
  67:              IQueryCollection queryParameters = httpContext.Request.Query;
  68:   
  69:              // If no query parameter "key" used, values will have 0 items
  70:              // If single value used for a key (...?key=v1), values will have 1 item ("v1")
  71:              // If key has multiple values (...?key=v1&key=v2), values will have 2 items ("v1" and "v2")
  72:              IList<string> values = queryParameters["key"];
  73:   
  74:              // If no query parameter "key" used, value will be ""
  75:              // If single value used for a key (...?key=v1), value will be "v1"
  76:              // If key has multiple values (...?key=v1&key=v2), value will be "v1,v2"
  77:              string value = queryParameters["key"].ToString();
  78:              #endregion
  79:   
  80:              // ASP.NET 4 - HttpContext.Request.Url and HttpContext.Request.RawUrl
  81:              #region snippet_Url
  82:              // using Microsoft.AspNetCore.Http.Extensions;
  83:              var url = httpContext.Request.GetDisplayUrl();
  84:              #endregion
  85:   
  86:              // ASP.NET 4 - HttpContext.Request.IsSecureConnection
  87:              #region snippet_Secure
  88:              var isSecureConnection = httpContext.Request.IsHttps;
  89:              #endregion
  90:   
  91:              // ASP.NET 4 - HttpContext.Request.UserHostAddress
  92:              #region snippet_Host
  93:              var userHostAddress = httpContext.Connection.RemoteIpAddress?.ToString();
  94:              #endregion
  95:   
  96:              // ASP.NET 4 - HttpContext.Request.Cookies 
  97:              #region snippet_Cookies
  98:              IRequestCookieCollection cookies = httpContext.Request.Cookies;
  99:              string unknownCookieValue = cookies["unknownCookie"]; // will be null (no exception)
 100:              string knownCookieValue = cookies["cookie1name"];     // will be actual value
 101:              #endregion
 102:   
 103:              // ASP.NET 4 - HttpContext.Request.RequestContext.RouteData
 104:              // using Microsoft.AspNetCore.Routing;
 105:              #region snippet_Route
 106:              var routeValue = httpContext.GetRouteValue("key");
 107:              #endregion
 108:   
 109:              // ASP.NET 4 - HttpContext.Request.Headers
 110:              #region snippet_Headers
 111:              // using Microsoft.AspNetCore.Http.Headers;
 112:              // using Microsoft.Net.Http.Headers;
 113:   
 114:              IHeaderDictionary headersDictionary = httpContext.Request.Headers;
 115:   
 116:              // GetTypedHeaders extension method provides strongly typed access to many headers
 117:              var requestHeaders = httpContext.Request.GetTypedHeaders();
 118:              CacheControlHeaderValue cacheControlHeaderValue = requestHeaders.CacheControl;
 119:   
 120:              // For unknown header, unknownheaderValues has zero items and unknownheaderValue is ""
 121:              IList<string> unknownheaderValues = headersDictionary["unknownheader"];
 122:              string unknownheaderValue = headersDictionary["unknownheader"].ToString();
 123:   
 124:              // For known header, knownheaderValues has 1 item and knownheaderValue is the value
 125:              IList<string> knownheaderValues = headersDictionary[HeaderNames.AcceptLanguage];
 126:              string knownheaderValue = headersDictionary[HeaderNames.AcceptLanguage].ToString();
 127:              #endregion
 128:   
 129:              // ASP.NET 4 - HttpContext.Request.UserAgent
 130:              #region snippet_Agent
 131:              string userAgent = headersDictionary[HeaderNames.UserAgent].ToString();
 132:              #endregion
 133:   
 134:              // ASP.NET 4 - HttpContext.Request.UrlReferrer
 135:              #region snippet_Referrer
 136:              string urlReferrer = headersDictionary[HeaderNames.Referer].ToString();
 137:              #endregion
 138:   
 139:              // ASP.NET 4 - HttpContext.Request.ContentType 
 140:              #region snippet_Type
 141:              // using Microsoft.Net.Http.Headers;
 142:   
 143:              MediaTypeHeaderValue mediaHeaderValue = requestHeaders.ContentType;
 144:              string contentType = mediaHeaderValue?.MediaType;   // ex. application/x-www-form-urlencoded
 145:              string contentMainType = mediaHeaderValue?.Type;    // ex. application
 146:              string contentSubType = mediaHeaderValue?.SubType;  // ex. x-www-form-urlencoded
 147:   
 148:              System.Text.Encoding requestEncoding = mediaHeaderValue?.Encoding;
 149:              #endregion
 150:   
 151:              // ASP.NET 4 - HttpContext.Request.Form 
 152:              #region snippet_Form
 153:              if (httpContext.Request.HasFormContentType)
 154:              {
 155:                  IFormCollection form;
 156:   
 157:                  form = httpContext.Request.Form; // sync
 158:                  // Or
 159:                  form = await httpContext.Request.ReadFormAsync(); // async
 160:   
 161:                  string firstName = form["firstname"];
 162:                  string lastName = form["lastname"];
 163:              }
 164:              #endregion
 165:   
 166:              // ----------
 167:              // See 
 168:              // http://stackoverflow.com/questions/31389781/read-body-twice-in-asp-net-5/
 169:   
 170:              // ASP.NET 4 - HttpContext.Request.InputStream
 171:              // Unlike reading the form, reading the raw body is not from a buffer.
 172:              // So you can only do this once per request.
 173:              // 
 174:              // If you need to read the body multiple times per request, see
 175:              // http://stackoverflow.com/questions/31389781/read-body-twice-in-asp-net-5/
 176:   
 177:              #region snippet_Input
 178:              string inputBody;
 179:              using (var reader = new System.IO.StreamReader(
 180:                  httpContext.Request.Body, System.Text.Encoding.UTF8))
 181:              {
 182:                  inputBody = reader.ReadToEnd();
 183:              }
 184:              #endregion
 185:   
 186:              // Use this middleware as a handler, so no call to 
 187:              // await _next.Invoke(aspnetCoreHttpContext);
 188:   
 189:              // ==================================================================
 190:              // Response
 191:   
 192:              // ASP.NET 4 - HttpContext.Response.Status  
 193:              // ASP.NET 4 - HttpContext.Response.StatusDescription (obsolete, removed from HTTP/2) 
 194:              #region snippet_Status
 195:              // using Microsoft.AspNetCore.Http;
 196:              httpContext.Response.StatusCode = StatusCodes.Status200OK;
 197:              #endregion
 198:   
 199:              // ASP.NET 4 - HttpContext.Response.ContentEncoding and HttpContext.Response.ContentType  
 200:              #region snippet_RespType
 201:              // using Microsoft.Net.Http.Headers;
 202:              var mediaType = new MediaTypeHeaderValue("application/json");
 203:              mediaType.Encoding = System.Text.Encoding.UTF8;
 204:              httpContext.Response.ContentType = mediaType.ToString();
 205:              #endregion
 206:   
 207:              // ASP.NET 4 - HttpContext.Response.ContentType only 
 208:              #region snippet_RespTypeOnly
 209:              httpContext.Response.ContentType = "text/html";
 210:              #endregion
 211:   
 212:              // ASP.NET 4 - HttpContext.Response.Output  
 213:              #region  snippet_Output
 214:              string responseContent = GetResponseContent();
 215:              await httpContext.Response.WriteAsync(responseContent);
 216:              #endregion
 217:          }
 218:   
 219:          #region snippet_SetHeaders
 220:          // using Microsoft.AspNet.Http.Headers;
 221:          // using Microsoft.Net.Http.Headers;
 222:   
 223:          private Task SetHeaders(object context)
 224:          {
 225:              var httpContext = (HttpContext)context;
 226:   
 227:              // Set header with single value
 228:              httpContext.Response.Headers["ResponseHeaderName"] = "headerValue";
 229:   
 230:              // Set header with multiple values
 231:              string[] responseHeaderValues = new string[] { "headerValue1", "headerValue1" };
 232:              httpContext.Response.Headers["ResponseHeaderName"] = responseHeaderValues;
 233:   
 234:              // Translating ASP.NET 4's HttpContext.Response.RedirectLocation  
 235:              httpContext.Response.Headers[HeaderNames.Location] = "http://www.example.com";
 236:              // Or
 237:              httpContext.Response.Redirect("http://www.example.com");
 238:   
 239:              // GetTypedHeaders extension method provides strongly typed access to many headers
 240:              var responseHeaders = httpContext.Response.GetTypedHeaders();
 241:   
 242:              // Translating ASP.NET 4's HttpContext.Response.CacheControl 
 243:              responseHeaders.CacheControl = new CacheControlHeaderValue
 244:              {
 245:                  MaxAge = new System.TimeSpan(365, 0, 0, 0)
 246:                  // Many more properties available 
 247:              };
 248:   
 249:              // If you use .Net 4.6+, Task.CompletedTask will be a bit faster
 250:              return Task.FromResult(0);
 251:          }
 252:          #endregion
 253:   
 254:          #region snippet_SetCookies
 255:          private Task SetCookies(object context)
 256:          {
 257:              var httpContext = (HttpContext)context;
 258:   
 259:              IResponseCookies responseCookies = httpContext.Response.Cookies;
 260:   
 261:              responseCookies.Append("cookie1name", "cookie1value");
 262:              responseCookies.Append("cookie2name", "cookie2value",
 263:                  new CookieOptions { Expires = System.DateTime.Now.AddDays(5), HttpOnly = true });
 264:   
 265:              // If you use .Net 4.6+, Task.CompletedTask will be a bit faster
 266:              return Task.FromResult(0); 
 267:          }
 268:          #endregion
 269:   
 270:          // You would normally use MVC to generate HTML like this.
 271:          private string GetResponseContent()
 272:          {
 273:              return @"
 274:  <!DOCTYPE html>
 275:  <html lang=""en"">
 276:  <head>
 277:      <title>index</title>
 278:  </head>
 279:  <body>
 280:  <form action=""form.context"" method=""post"">
 281:      <input type=""text"" name=""firstname"">
 282:      <input type=""text"" name=""lastname"">
 283:      <input type=""submit"" value=""Submit"">
 284:  </form> 
 285:  </body>
 286:  </html>
 287:  ";
 288:          }
 289:      }
 290:   
 291:      public static class HttpContextDemoMiddlewareExtensions
 292:      {
 293:          public static IApplicationBuilder UseHttpContextDemoMiddleware(this IApplicationBuilder builder)
 294:          {
 295:              return builder.UseMiddleware<HttpContextDemoMiddleware>();
 296:          }
 297:      }
 298:  }

HttpContext.Response.Output translates to:

[!code-csharpMain]

   1:  using Microsoft.AspNetCore.Builder;
   2:  using Microsoft.AspNetCore.Http;
   3:  using System.Collections.Generic;
   4:  using System.Threading.Tasks;
   5:  using Microsoft.Net.Http.Headers;
   6:  using Microsoft.AspNetCore.Http.Extensions;
   7:  using Microsoft.AspNetCore.Routing;
   8:   
   9:  namespace MyApp.Middleware
  10:  {
  11:      public class HttpContextDemoMiddleware
  12:      {
  13:          private readonly RequestDelegate _next;
  14:   
  15:          public HttpContextDemoMiddleware(RequestDelegate next)
  16:          {
  17:              _next = next;
  18:          }
  19:   
  20:          public async Task Invoke(HttpContext httpContext)
  21:          {
  22:              // OnStarting handlers have to be set early during request processing,
  23:              // even though they are used to create the response.
  24:   
  25:              // ----------------------
  26:              // ASP.NET 4 - HttpContext.Response.Headers  
  27:              // ASP.NET 4 - HttpContext.Response.Cookies  
  28:              // 
  29:              // Issue with all response headers is that they will not be sent 
  30:              // after anything has been written to the response body.
  31:              // To solve this, use OnStarting to set a callback that will be called 
  32:              // right before headers are sent. Set the headers in that callback.
  33:              //
  34:              // Setting a cookie results in a Set-Cookie response header.
  35:              // So use an OnStarting handler here as well.
  36:   
  37:              //>40
  38:              httpContext.Response.OnStarting(SetHeaders, state: httpContext);
  39:              httpContext.Response.OnStarting(SetCookies, state: httpContext);
  40:              //<40
  41:   
  42:              // ==================================================================
  43:              // Context
  44:   
  45:              // Unique request ID (no ASP.NET 4 counterpart)
  46:              #region snippet_Trace
  47:              string requestId = httpContext.TraceIdentifier;
  48:              #endregion
  49:   
  50:              // ASP.NET 4 - HttpContext.Items
  51:              #region snippet_Items
  52:              IDictionary<object, object> items = httpContext.Items;
  53:              #endregion
  54:   
  55:              // ==================================================================
  56:              // Request
  57:   
  58:              // ASP.NET 4 - HttpContext.Request.HttpMethod
  59:              #region snippet_Method
  60:              string httpMethod = httpContext.Request.Method;
  61:              #endregion
  62:   
  63:              // ----------
  64:   
  65:              // ASP.NET 4 - HttpContext.Request.QueryString
  66:              #region snippet_Query
  67:              IQueryCollection queryParameters = httpContext.Request.Query;
  68:   
  69:              // If no query parameter "key" used, values will have 0 items
  70:              // If single value used for a key (...?key=v1), values will have 1 item ("v1")
  71:              // If key has multiple values (...?key=v1&key=v2), values will have 2 items ("v1" and "v2")
  72:              IList<string> values = queryParameters["key"];
  73:   
  74:              // If no query parameter "key" used, value will be ""
  75:              // If single value used for a key (...?key=v1), value will be "v1"
  76:              // If key has multiple values (...?key=v1&key=v2), value will be "v1,v2"
  77:              string value = queryParameters["key"].ToString();
  78:              #endregion
  79:   
  80:              // ASP.NET 4 - HttpContext.Request.Url and HttpContext.Request.RawUrl
  81:              #region snippet_Url
  82:              // using Microsoft.AspNetCore.Http.Extensions;
  83:              var url = httpContext.Request.GetDisplayUrl();
  84:              #endregion
  85:   
  86:              // ASP.NET 4 - HttpContext.Request.IsSecureConnection
  87:              #region snippet_Secure
  88:              var isSecureConnection = httpContext.Request.IsHttps;
  89:              #endregion
  90:   
  91:              // ASP.NET 4 - HttpContext.Request.UserHostAddress
  92:              #region snippet_Host
  93:              var userHostAddress = httpContext.Connection.RemoteIpAddress?.ToString();
  94:              #endregion
  95:   
  96:              // ASP.NET 4 - HttpContext.Request.Cookies 
  97:              #region snippet_Cookies
  98:              IRequestCookieCollection cookies = httpContext.Request.Cookies;
  99:              string unknownCookieValue = cookies["unknownCookie"]; // will be null (no exception)
 100:              string knownCookieValue = cookies["cookie1name"];     // will be actual value
 101:              #endregion
 102:   
 103:              // ASP.NET 4 - HttpContext.Request.RequestContext.RouteData
 104:              // using Microsoft.AspNetCore.Routing;
 105:              #region snippet_Route
 106:              var routeValue = httpContext.GetRouteValue("key");
 107:              #endregion
 108:   
 109:              // ASP.NET 4 - HttpContext.Request.Headers
 110:              #region snippet_Headers
 111:              // using Microsoft.AspNetCore.Http.Headers;
 112:              // using Microsoft.Net.Http.Headers;
 113:   
 114:              IHeaderDictionary headersDictionary = httpContext.Request.Headers;
 115:   
 116:              // GetTypedHeaders extension method provides strongly typed access to many headers
 117:              var requestHeaders = httpContext.Request.GetTypedHeaders();
 118:              CacheControlHeaderValue cacheControlHeaderValue = requestHeaders.CacheControl;
 119:   
 120:              // For unknown header, unknownheaderValues has zero items and unknownheaderValue is ""
 121:              IList<string> unknownheaderValues = headersDictionary["unknownheader"];
 122:              string unknownheaderValue = headersDictionary["unknownheader"].ToString();
 123:   
 124:              // For known header, knownheaderValues has 1 item and knownheaderValue is the value
 125:              IList<string> knownheaderValues = headersDictionary[HeaderNames.AcceptLanguage];
 126:              string knownheaderValue = headersDictionary[HeaderNames.AcceptLanguage].ToString();
 127:              #endregion
 128:   
 129:              // ASP.NET 4 - HttpContext.Request.UserAgent
 130:              #region snippet_Agent
 131:              string userAgent = headersDictionary[HeaderNames.UserAgent].ToString();
 132:              #endregion
 133:   
 134:              // ASP.NET 4 - HttpContext.Request.UrlReferrer
 135:              #region snippet_Referrer
 136:              string urlReferrer = headersDictionary[HeaderNames.Referer].ToString();
 137:              #endregion
 138:   
 139:              // ASP.NET 4 - HttpContext.Request.ContentType 
 140:              #region snippet_Type
 141:              // using Microsoft.Net.Http.Headers;
 142:   
 143:              MediaTypeHeaderValue mediaHeaderValue = requestHeaders.ContentType;
 144:              string contentType = mediaHeaderValue?.MediaType;   // ex. application/x-www-form-urlencoded
 145:              string contentMainType = mediaHeaderValue?.Type;    // ex. application
 146:              string contentSubType = mediaHeaderValue?.SubType;  // ex. x-www-form-urlencoded
 147:   
 148:              System.Text.Encoding requestEncoding = mediaHeaderValue?.Encoding;
 149:              #endregion
 150:   
 151:              // ASP.NET 4 - HttpContext.Request.Form 
 152:              #region snippet_Form
 153:              if (httpContext.Request.HasFormContentType)
 154:              {
 155:                  IFormCollection form;
 156:   
 157:                  form = httpContext.Request.Form; // sync
 158:                  // Or
 159:                  form = await httpContext.Request.ReadFormAsync(); // async
 160:   
 161:                  string firstName = form["firstname"];
 162:                  string lastName = form["lastname"];
 163:              }
 164:              #endregion
 165:   
 166:              // ----------
 167:              // See 
 168:              // http://stackoverflow.com/questions/31389781/read-body-twice-in-asp-net-5/
 169:   
 170:              // ASP.NET 4 - HttpContext.Request.InputStream
 171:              // Unlike reading the form, reading the raw body is not from a buffer.
 172:              // So you can only do this once per request.
 173:              // 
 174:              // If you need to read the body multiple times per request, see
 175:              // http://stackoverflow.com/questions/31389781/read-body-twice-in-asp-net-5/
 176:   
 177:              #region snippet_Input
 178:              string inputBody;
 179:              using (var reader = new System.IO.StreamReader(
 180:                  httpContext.Request.Body, System.Text.Encoding.UTF8))
 181:              {
 182:                  inputBody = reader.ReadToEnd();
 183:              }
 184:              #endregion
 185:   
 186:              // Use this middleware as a handler, so no call to 
 187:              // await _next.Invoke(aspnetCoreHttpContext);
 188:   
 189:              // ==================================================================
 190:              // Response
 191:   
 192:              // ASP.NET 4 - HttpContext.Response.Status  
 193:              // ASP.NET 4 - HttpContext.Response.StatusDescription (obsolete, removed from HTTP/2) 
 194:              #region snippet_Status
 195:              // using Microsoft.AspNetCore.Http;
 196:              httpContext.Response.StatusCode = StatusCodes.Status200OK;
 197:              #endregion
 198:   
 199:              // ASP.NET 4 - HttpContext.Response.ContentEncoding and HttpContext.Response.ContentType  
 200:              #region snippet_RespType
 201:              // using Microsoft.Net.Http.Headers;
 202:              var mediaType = new MediaTypeHeaderValue("application/json");
 203:              mediaType.Encoding = System.Text.Encoding.UTF8;
 204:              httpContext.Response.ContentType = mediaType.ToString();
 205:              #endregion
 206:   
 207:              // ASP.NET 4 - HttpContext.Response.ContentType only 
 208:              #region snippet_RespTypeOnly
 209:              httpContext.Response.ContentType = "text/html";
 210:              #endregion
 211:   
 212:              // ASP.NET 4 - HttpContext.Response.Output  
 213:              #region  snippet_Output
 214:              string responseContent = GetResponseContent();
 215:              await httpContext.Response.WriteAsync(responseContent);
 216:              #endregion
 217:          }
 218:   
 219:          #region snippet_SetHeaders
 220:          // using Microsoft.AspNet.Http.Headers;
 221:          // using Microsoft.Net.Http.Headers;
 222:   
 223:          private Task SetHeaders(object context)
 224:          {
 225:              var httpContext = (HttpContext)context;
 226:   
 227:              // Set header with single value
 228:              httpContext.Response.Headers["ResponseHeaderName"] = "headerValue";
 229:   
 230:              // Set header with multiple values
 231:              string[] responseHeaderValues = new string[] { "headerValue1", "headerValue1" };
 232:              httpContext.Response.Headers["ResponseHeaderName"] = responseHeaderValues;
 233:   
 234:              // Translating ASP.NET 4's HttpContext.Response.RedirectLocation  
 235:              httpContext.Response.Headers[HeaderNames.Location] = "http://www.example.com";
 236:              // Or
 237:              httpContext.Response.Redirect("http://www.example.com");
 238:   
 239:              // GetTypedHeaders extension method provides strongly typed access to many headers
 240:              var responseHeaders = httpContext.Response.GetTypedHeaders();
 241:   
 242:              // Translating ASP.NET 4's HttpContext.Response.CacheControl 
 243:              responseHeaders.CacheControl = new CacheControlHeaderValue
 244:              {
 245:                  MaxAge = new System.TimeSpan(365, 0, 0, 0)
 246:                  // Many more properties available 
 247:              };
 248:   
 249:              // If you use .Net 4.6+, Task.CompletedTask will be a bit faster
 250:              return Task.FromResult(0);
 251:          }
 252:          #endregion
 253:   
 254:          #region snippet_SetCookies
 255:          private Task SetCookies(object context)
 256:          {
 257:              var httpContext = (HttpContext)context;
 258:   
 259:              IResponseCookies responseCookies = httpContext.Response.Cookies;
 260:   
 261:              responseCookies.Append("cookie1name", "cookie1value");
 262:              responseCookies.Append("cookie2name", "cookie2value",
 263:                  new CookieOptions { Expires = System.DateTime.Now.AddDays(5), HttpOnly = true });
 264:   
 265:              // If you use .Net 4.6+, Task.CompletedTask will be a bit faster
 266:              return Task.FromResult(0); 
 267:          }
 268:          #endregion
 269:   
 270:          // You would normally use MVC to generate HTML like this.
 271:          private string GetResponseContent()
 272:          {
 273:              return @"
 274:  <!DOCTYPE html>
 275:  <html lang=""en"">
 276:  <head>
 277:      <title>index</title>
 278:  </head>
 279:  <body>
 280:  <form action=""form.context"" method=""post"">
 281:      <input type=""text"" name=""firstname"">
 282:      <input type=""text"" name=""lastname"">
 283:      <input type=""submit"" value=""Submit"">
 284:  </form> 
 285:  </body>
 286:  </html>
 287:  ";
 288:          }
 289:      }
 290:   
 291:      public static class HttpContextDemoMiddlewareExtensions
 292:      {
 293:          public static IApplicationBuilder UseHttpContextDemoMiddleware(this IApplicationBuilder builder)
 294:          {
 295:              return builder.UseMiddleware<HttpContextDemoMiddleware>();
 296:          }
 297:      }
 298:  }

HttpContext.Response.TransmitFile

Serving up a file is discussed here.

HttpContext.Response.Headers

Sending response headers is complicated by the fact that if you set them after anything has been written to the response body, they will not be sent.

The solution is to set a callback method that will be called right before writing to the response starts. This is best done at the start of the Invoke method in your middleware. It is this callback method that sets your response headers.

The following code sets a callback method called SetHeaders:

The SetHeaders callback method would look like this:

[!code-csharpMain]

   1:  using Microsoft.AspNetCore.Builder;
   2:  using Microsoft.AspNetCore.Http;
   3:  using System.Collections.Generic;
   4:  using System.Threading.Tasks;
   5:  using Microsoft.Net.Http.Headers;
   6:  using Microsoft.AspNetCore.Http.Extensions;
   7:  using Microsoft.AspNetCore.Routing;
   8:   
   9:  namespace MyApp.Middleware
  10:  {
  11:      public class HttpContextDemoMiddleware
  12:      {
  13:          private readonly RequestDelegate _next;
  14:   
  15:          public HttpContextDemoMiddleware(RequestDelegate next)
  16:          {
  17:              _next = next;
  18:          }
  19:   
  20:          public async Task Invoke(HttpContext httpContext)
  21:          {
  22:              // OnStarting handlers have to be set early during request processing,
  23:              // even though they are used to create the response.
  24:   
  25:              // ----------------------
  26:              // ASP.NET 4 - HttpContext.Response.Headers  
  27:              // ASP.NET 4 - HttpContext.Response.Cookies  
  28:              // 
  29:              // Issue with all response headers is that they will not be sent 
  30:              // after anything has been written to the response body.
  31:              // To solve this, use OnStarting to set a callback that will be called 
  32:              // right before headers are sent. Set the headers in that callback.
  33:              //
  34:              // Setting a cookie results in a Set-Cookie response header.
  35:              // So use an OnStarting handler here as well.
  36:   
  37:              //>40
  38:              httpContext.Response.OnStarting(SetHeaders, state: httpContext);
  39:              httpContext.Response.OnStarting(SetCookies, state: httpContext);
  40:              //<40
  41:   
  42:              // ==================================================================
  43:              // Context
  44:   
  45:              // Unique request ID (no ASP.NET 4 counterpart)
  46:              #region snippet_Trace
  47:              string requestId = httpContext.TraceIdentifier;
  48:              #endregion
  49:   
  50:              // ASP.NET 4 - HttpContext.Items
  51:              #region snippet_Items
  52:              IDictionary<object, object> items = httpContext.Items;
  53:              #endregion
  54:   
  55:              // ==================================================================
  56:              // Request
  57:   
  58:              // ASP.NET 4 - HttpContext.Request.HttpMethod
  59:              #region snippet_Method
  60:              string httpMethod = httpContext.Request.Method;
  61:              #endregion
  62:   
  63:              // ----------
  64:   
  65:              // ASP.NET 4 - HttpContext.Request.QueryString
  66:              #region snippet_Query
  67:              IQueryCollection queryParameters = httpContext.Request.Query;
  68:   
  69:              // If no query parameter "key" used, values will have 0 items
  70:              // If single value used for a key (...?key=v1), values will have 1 item ("v1")
  71:              // If key has multiple values (...?key=v1&key=v2), values will have 2 items ("v1" and "v2")
  72:              IList<string> values = queryParameters["key"];
  73:   
  74:              // If no query parameter "key" used, value will be ""
  75:              // If single value used for a key (...?key=v1), value will be "v1"
  76:              // If key has multiple values (...?key=v1&key=v2), value will be "v1,v2"
  77:              string value = queryParameters["key"].ToString();
  78:              #endregion
  79:   
  80:              // ASP.NET 4 - HttpContext.Request.Url and HttpContext.Request.RawUrl
  81:              #region snippet_Url
  82:              // using Microsoft.AspNetCore.Http.Extensions;
  83:              var url = httpContext.Request.GetDisplayUrl();
  84:              #endregion
  85:   
  86:              // ASP.NET 4 - HttpContext.Request.IsSecureConnection
  87:              #region snippet_Secure
  88:              var isSecureConnection = httpContext.Request.IsHttps;
  89:              #endregion
  90:   
  91:              // ASP.NET 4 - HttpContext.Request.UserHostAddress
  92:              #region snippet_Host
  93:              var userHostAddress = httpContext.Connection.RemoteIpAddress?.ToString();
  94:              #endregion
  95:   
  96:              // ASP.NET 4 - HttpContext.Request.Cookies 
  97:              #region snippet_Cookies
  98:              IRequestCookieCollection cookies = httpContext.Request.Cookies;
  99:              string unknownCookieValue = cookies["unknownCookie"]; // will be null (no exception)
 100:              string knownCookieValue = cookies["cookie1name"];     // will be actual value
 101:              #endregion
 102:   
 103:              // ASP.NET 4 - HttpContext.Request.RequestContext.RouteData
 104:              // using Microsoft.AspNetCore.Routing;
 105:              #region snippet_Route
 106:              var routeValue = httpContext.GetRouteValue("key");
 107:              #endregion
 108:   
 109:              // ASP.NET 4 - HttpContext.Request.Headers
 110:              #region snippet_Headers
 111:              // using Microsoft.AspNetCore.Http.Headers;
 112:              // using Microsoft.Net.Http.Headers;
 113:   
 114:              IHeaderDictionary headersDictionary = httpContext.Request.Headers;
 115:   
 116:              // GetTypedHeaders extension method provides strongly typed access to many headers
 117:              var requestHeaders = httpContext.Request.GetTypedHeaders();
 118:              CacheControlHeaderValue cacheControlHeaderValue = requestHeaders.CacheControl;
 119:   
 120:              // For unknown header, unknownheaderValues has zero items and unknownheaderValue is ""
 121:              IList<string> unknownheaderValues = headersDictionary["unknownheader"];
 122:              string unknownheaderValue = headersDictionary["unknownheader"].ToString();
 123:   
 124:              // For known header, knownheaderValues has 1 item and knownheaderValue is the value
 125:              IList<string> knownheaderValues = headersDictionary[HeaderNames.AcceptLanguage];
 126:              string knownheaderValue = headersDictionary[HeaderNames.AcceptLanguage].ToString();
 127:              #endregion
 128:   
 129:              // ASP.NET 4 - HttpContext.Request.UserAgent
 130:              #region snippet_Agent
 131:              string userAgent = headersDictionary[HeaderNames.UserAgent].ToString();
 132:              #endregion
 133:   
 134:              // ASP.NET 4 - HttpContext.Request.UrlReferrer
 135:              #region snippet_Referrer
 136:              string urlReferrer = headersDictionary[HeaderNames.Referer].ToString();
 137:              #endregion
 138:   
 139:              // ASP.NET 4 - HttpContext.Request.ContentType 
 140:              #region snippet_Type
 141:              // using Microsoft.Net.Http.Headers;
 142:   
 143:              MediaTypeHeaderValue mediaHeaderValue = requestHeaders.ContentType;
 144:              string contentType = mediaHeaderValue?.MediaType;   // ex. application/x-www-form-urlencoded
 145:              string contentMainType = mediaHeaderValue?.Type;    // ex. application
 146:              string contentSubType = mediaHeaderValue?.SubType;  // ex. x-www-form-urlencoded
 147:   
 148:              System.Text.Encoding requestEncoding = mediaHeaderValue?.Encoding;
 149:              #endregion
 150:   
 151:              // ASP.NET 4 - HttpContext.Request.Form 
 152:              #region snippet_Form
 153:              if (httpContext.Request.HasFormContentType)
 154:              {
 155:                  IFormCollection form;
 156:   
 157:                  form = httpContext.Request.Form; // sync
 158:                  // Or
 159:                  form = await httpContext.Request.ReadFormAsync(); // async
 160:   
 161:                  string firstName = form["firstname"];
 162:                  string lastName = form["lastname"];
 163:              }
 164:              #endregion
 165:   
 166:              // ----------
 167:              // See 
 168:              // http://stackoverflow.com/questions/31389781/read-body-twice-in-asp-net-5/
 169:   
 170:              // ASP.NET 4 - HttpContext.Request.InputStream
 171:              // Unlike reading the form, reading the raw body is not from a buffer.
 172:              // So you can only do this once per request.
 173:              // 
 174:              // If you need to read the body multiple times per request, see
 175:              // http://stackoverflow.com/questions/31389781/read-body-twice-in-asp-net-5/
 176:   
 177:              #region snippet_Input
 178:              string inputBody;
 179:              using (var reader = new System.IO.StreamReader(
 180:                  httpContext.Request.Body, System.Text.Encoding.UTF8))
 181:              {
 182:                  inputBody = reader.ReadToEnd();
 183:              }
 184:              #endregion
 185:   
 186:              // Use this middleware as a handler, so no call to 
 187:              // await _next.Invoke(aspnetCoreHttpContext);
 188:   
 189:              // ==================================================================
 190:              // Response
 191:   
 192:              // ASP.NET 4 - HttpContext.Response.Status  
 193:              // ASP.NET 4 - HttpContext.Response.StatusDescription (obsolete, removed from HTTP/2) 
 194:              #region snippet_Status
 195:              // using Microsoft.AspNetCore.Http;
 196:              httpContext.Response.StatusCode = StatusCodes.Status200OK;
 197:              #endregion
 198:   
 199:              // ASP.NET 4 - HttpContext.Response.ContentEncoding and HttpContext.Response.ContentType  
 200:              #region snippet_RespType
 201:              // using Microsoft.Net.Http.Headers;
 202:              var mediaType = new MediaTypeHeaderValue("application/json");
 203:              mediaType.Encoding = System.Text.Encoding.UTF8;
 204:              httpContext.Response.ContentType = mediaType.ToString();
 205:              #endregion
 206:   
 207:              // ASP.NET 4 - HttpContext.Response.ContentType only 
 208:              #region snippet_RespTypeOnly
 209:              httpContext.Response.ContentType = "text/html";
 210:              #endregion
 211:   
 212:              // ASP.NET 4 - HttpContext.Response.Output  
 213:              #region  snippet_Output
 214:              string responseContent = GetResponseContent();
 215:              await httpContext.Response.WriteAsync(responseContent);
 216:              #endregion
 217:          }
 218:   
 219:          #region snippet_SetHeaders
 220:          // using Microsoft.AspNet.Http.Headers;
 221:          // using Microsoft.Net.Http.Headers;
 222:   
 223:          private Task SetHeaders(object context)
 224:          {
 225:              var httpContext = (HttpContext)context;
 226:   
 227:              // Set header with single value
 228:              httpContext.Response.Headers["ResponseHeaderName"] = "headerValue";
 229:   
 230:              // Set header with multiple values
 231:              string[] responseHeaderValues = new string[] { "headerValue1", "headerValue1" };
 232:              httpContext.Response.Headers["ResponseHeaderName"] = responseHeaderValues;
 233:   
 234:              // Translating ASP.NET 4's HttpContext.Response.RedirectLocation  
 235:              httpContext.Response.Headers[HeaderNames.Location] = "http://www.example.com";
 236:              // Or
 237:              httpContext.Response.Redirect("http://www.example.com");
 238:   
 239:              // GetTypedHeaders extension method provides strongly typed access to many headers
 240:              var responseHeaders = httpContext.Response.GetTypedHeaders();
 241:   
 242:              // Translating ASP.NET 4's HttpContext.Response.CacheControl 
 243:              responseHeaders.CacheControl = new CacheControlHeaderValue
 244:              {
 245:                  MaxAge = new System.TimeSpan(365, 0, 0, 0)
 246:                  // Many more properties available 
 247:              };
 248:   
 249:              // If you use .Net 4.6+, Task.CompletedTask will be a bit faster
 250:              return Task.FromResult(0);
 251:          }
 252:          #endregion
 253:   
 254:          #region snippet_SetCookies
 255:          private Task SetCookies(object context)
 256:          {
 257:              var httpContext = (HttpContext)context;
 258:   
 259:              IResponseCookies responseCookies = httpContext.Response.Cookies;
 260:   
 261:              responseCookies.Append("cookie1name", "cookie1value");
 262:              responseCookies.Append("cookie2name", "cookie2value",
 263:                  new CookieOptions { Expires = System.DateTime.Now.AddDays(5), HttpOnly = true });
 264:   
 265:              // If you use .Net 4.6+, Task.CompletedTask will be a bit faster
 266:              return Task.FromResult(0); 
 267:          }
 268:          #endregion
 269:   
 270:          // You would normally use MVC to generate HTML like this.
 271:          private string GetResponseContent()
 272:          {
 273:              return @"
 274:  <!DOCTYPE html>
 275:  <html lang=""en"">
 276:  <head>
 277:      <title>index</title>
 278:  </head>
 279:  <body>
 280:  <form action=""form.context"" method=""post"">
 281:      <input type=""text"" name=""firstname"">
 282:      <input type=""text"" name=""lastname"">
 283:      <input type=""submit"" value=""Submit"">
 284:  </form> 
 285:  </body>
 286:  </html>
 287:  ";
 288:          }
 289:      }
 290:   
 291:      public static class HttpContextDemoMiddlewareExtensions
 292:      {
 293:          public static IApplicationBuilder UseHttpContextDemoMiddleware(this IApplicationBuilder builder)
 294:          {
 295:              return builder.UseMiddleware<HttpContextDemoMiddleware>();
 296:          }
 297:      }
 298:  }

HttpContext.Response.Cookies

Cookies travel to the browser in a Set-Cookie response header. As a result, sending cookies requires the same callback as used for sending response headers:

The SetCookies callback method would look like the following:

[!code-csharpMain]

   1:  using Microsoft.AspNetCore.Builder;
   2:  using Microsoft.AspNetCore.Http;
   3:  using System.Collections.Generic;
   4:  using System.Threading.Tasks;
   5:  using Microsoft.Net.Http.Headers;
   6:  using Microsoft.AspNetCore.Http.Extensions;
   7:  using Microsoft.AspNetCore.Routing;
   8:   
   9:  namespace MyApp.Middleware
  10:  {
  11:      public class HttpContextDemoMiddleware
  12:      {
  13:          private readonly RequestDelegate _next;
  14:   
  15:          public HttpContextDemoMiddleware(RequestDelegate next)
  16:          {
  17:              _next = next;
  18:          }
  19:   
  20:          public async Task Invoke(HttpContext httpContext)
  21:          {
  22:              // OnStarting handlers have to be set early during request processing,
  23:              // even though they are used to create the response.
  24:   
  25:              // ----------------------
  26:              // ASP.NET 4 - HttpContext.Response.Headers  
  27:              // ASP.NET 4 - HttpContext.Response.Cookies  
  28:              // 
  29:              // Issue with all response headers is that they will not be sent 
  30:              // after anything has been written to the response body.
  31:              // To solve this, use OnStarting to set a callback that will be called 
  32:              // right before headers are sent. Set the headers in that callback.
  33:              //
  34:              // Setting a cookie results in a Set-Cookie response header.
  35:              // So use an OnStarting handler here as well.
  36:   
  37:              //>40
  38:              httpContext.Response.OnStarting(SetHeaders, state: httpContext);
  39:              httpContext.Response.OnStarting(SetCookies, state: httpContext);
  40:              //<40
  41:   
  42:              // ==================================================================
  43:              // Context
  44:   
  45:              // Unique request ID (no ASP.NET 4 counterpart)
  46:              #region snippet_Trace
  47:              string requestId = httpContext.TraceIdentifier;
  48:              #endregion
  49:   
  50:              // ASP.NET 4 - HttpContext.Items
  51:              #region snippet_Items
  52:              IDictionary<object, object> items = httpContext.Items;
  53:              #endregion
  54:   
  55:              // ==================================================================
  56:              // Request
  57:   
  58:              // ASP.NET 4 - HttpContext.Request.HttpMethod
  59:              #region snippet_Method
  60:              string httpMethod = httpContext.Request.Method;
  61:              #endregion
  62:   
  63:              // ----------
  64:   
  65:              // ASP.NET 4 - HttpContext.Request.QueryString
  66:              #region snippet_Query
  67:              IQueryCollection queryParameters = httpContext.Request.Query;
  68:   
  69:              // If no query parameter "key" used, values will have 0 items
  70:              // If single value used for a key (...?key=v1), values will have 1 item ("v1")
  71:              // If key has multiple values (...?key=v1&key=v2), values will have 2 items ("v1" and "v2")
  72:              IList<string> values = queryParameters["key"];
  73:   
  74:              // If no query parameter "key" used, value will be ""
  75:              // If single value used for a key (...?key=v1), value will be "v1"
  76:              // If key has multiple values (...?key=v1&key=v2), value will be "v1,v2"
  77:              string value = queryParameters["key"].ToString();
  78:              #endregion
  79:   
  80:              // ASP.NET 4 - HttpContext.Request.Url and HttpContext.Request.RawUrl
  81:              #region snippet_Url
  82:              // using Microsoft.AspNetCore.Http.Extensions;
  83:              var url = httpContext.Request.GetDisplayUrl();
  84:              #endregion
  85:   
  86:              // ASP.NET 4 - HttpContext.Request.IsSecureConnection
  87:              #region snippet_Secure
  88:              var isSecureConnection = httpContext.Request.IsHttps;
  89:              #endregion
  90:   
  91:              // ASP.NET 4 - HttpContext.Request.UserHostAddress
  92:              #region snippet_Host
  93:              var userHostAddress = httpContext.Connection.RemoteIpAddress?.ToString();
  94:              #endregion
  95:   
  96:              // ASP.NET 4 - HttpContext.Request.Cookies 
  97:              #region snippet_Cookies
  98:              IRequestCookieCollection cookies = httpContext.Request.Cookies;
  99:              string unknownCookieValue = cookies["unknownCookie"]; // will be null (no exception)
 100:              string knownCookieValue = cookies["cookie1name"];     // will be actual value
 101:              #endregion
 102:   
 103:              // ASP.NET 4 - HttpContext.Request.RequestContext.RouteData
 104:              // using Microsoft.AspNetCore.Routing;
 105:              #region snippet_Route
 106:              var routeValue = httpContext.GetRouteValue("key");
 107:              #endregion
 108:   
 109:              // ASP.NET 4 - HttpContext.Request.Headers
 110:              #region snippet_Headers
 111:              // using Microsoft.AspNetCore.Http.Headers;
 112:              // using Microsoft.Net.Http.Headers;
 113:   
 114:              IHeaderDictionary headersDictionary = httpContext.Request.Headers;
 115:   
 116:              // GetTypedHeaders extension method provides strongly typed access to many headers
 117:              var requestHeaders = httpContext.Request.GetTypedHeaders();
 118:              CacheControlHeaderValue cacheControlHeaderValue = requestHeaders.CacheControl;
 119:   
 120:              // For unknown header, unknownheaderValues has zero items and unknownheaderValue is ""
 121:              IList<string> unknownheaderValues = headersDictionary["unknownheader"];
 122:              string unknownheaderValue = headersDictionary["unknownheader"].ToString();
 123:   
 124:              // For known header, knownheaderValues has 1 item and knownheaderValue is the value
 125:              IList<string> knownheaderValues = headersDictionary[HeaderNames.AcceptLanguage];
 126:              string knownheaderValue = headersDictionary[HeaderNames.AcceptLanguage].ToString();
 127:              #endregion
 128:   
 129:              // ASP.NET 4 - HttpContext.Request.UserAgent
 130:              #region snippet_Agent
 131:              string userAgent = headersDictionary[HeaderNames.UserAgent].ToString();
 132:              #endregion
 133:   
 134:              // ASP.NET 4 - HttpContext.Request.UrlReferrer
 135:              #region snippet_Referrer
 136:              string urlReferrer = headersDictionary[HeaderNames.Referer].ToString();
 137:              #endregion
 138:   
 139:              // ASP.NET 4 - HttpContext.Request.ContentType 
 140:              #region snippet_Type
 141:              // using Microsoft.Net.Http.Headers;
 142:   
 143:              MediaTypeHeaderValue mediaHeaderValue = requestHeaders.ContentType;
 144:              string contentType = mediaHeaderValue?.MediaType;   // ex. application/x-www-form-urlencoded
 145:              string contentMainType = mediaHeaderValue?.Type;    // ex. application
 146:              string contentSubType = mediaHeaderValue?.SubType;  // ex. x-www-form-urlencoded
 147:   
 148:              System.Text.Encoding requestEncoding = mediaHeaderValue?.Encoding;
 149:              #endregion
 150:   
 151:              // ASP.NET 4 - HttpContext.Request.Form 
 152:              #region snippet_Form
 153:              if (httpContext.Request.HasFormContentType)
 154:              {
 155:                  IFormCollection form;
 156:   
 157:                  form = httpContext.Request.Form; // sync
 158:                  // Or
 159:                  form = await httpContext.Request.ReadFormAsync(); // async
 160:   
 161:                  string firstName = form["firstname"];
 162:                  string lastName = form["lastname"];
 163:              }
 164:              #endregion
 165:   
 166:              // ----------
 167:              // See 
 168:              // http://stackoverflow.com/questions/31389781/read-body-twice-in-asp-net-5/
 169:   
 170:              // ASP.NET 4 - HttpContext.Request.InputStream
 171:              // Unlike reading the form, reading the raw body is not from a buffer.
 172:              // So you can only do this once per request.
 173:              // 
 174:              // If you need to read the body multiple times per request, see
 175:              // http://stackoverflow.com/questions/31389781/read-body-twice-in-asp-net-5/
 176:   
 177:              #region snippet_Input
 178:              string inputBody;
 179:              using (var reader = new System.IO.StreamReader(
 180:                  httpContext.Request.Body, System.Text.Encoding.UTF8))
 181:              {
 182:                  inputBody = reader.ReadToEnd();
 183:              }
 184:              #endregion
 185:   
 186:              // Use this middleware as a handler, so no call to 
 187:              // await _next.Invoke(aspnetCoreHttpContext);
 188:   
 189:              // ==================================================================
 190:              // Response
 191:   
 192:              // ASP.NET 4 - HttpContext.Response.Status  
 193:              // ASP.NET 4 - HttpContext.Response.StatusDescription (obsolete, removed from HTTP/2) 
 194:              #region snippet_Status
 195:              // using Microsoft.AspNetCore.Http;
 196:              httpContext.Response.StatusCode = StatusCodes.Status200OK;
 197:              #endregion
 198:   
 199:              // ASP.NET 4 - HttpContext.Response.ContentEncoding and HttpContext.Response.ContentType  
 200:              #region snippet_RespType
 201:              // using Microsoft.Net.Http.Headers;
 202:              var mediaType = new MediaTypeHeaderValue("application/json");
 203:              mediaType.Encoding = System.Text.Encoding.UTF8;
 204:              httpContext.Response.ContentType = mediaType.ToString();
 205:              #endregion
 206:   
 207:              // ASP.NET 4 - HttpContext.Response.ContentType only 
 208:              #region snippet_RespTypeOnly
 209:              httpContext.Response.ContentType = "text/html";
 210:              #endregion
 211:   
 212:              // ASP.NET 4 - HttpContext.Response.Output  
 213:              #region  snippet_Output
 214:              string responseContent = GetResponseContent();
 215:              await httpContext.Response.WriteAsync(responseContent);
 216:              #endregion
 217:          }
 218:   
 219:          #region snippet_SetHeaders
 220:          // using Microsoft.AspNet.Http.Headers;
 221:          // using Microsoft.Net.Http.Headers;
 222:   
 223:          private Task SetHeaders(object context)
 224:          {
 225:              var httpContext = (HttpContext)context;
 226:   
 227:              // Set header with single value
 228:              httpContext.Response.Headers["ResponseHeaderName"] = "headerValue";
 229:   
 230:              // Set header with multiple values
 231:              string[] responseHeaderValues = new string[] { "headerValue1", "headerValue1" };
 232:              httpContext.Response.Headers["ResponseHeaderName"] = responseHeaderValues;
 233:   
 234:              // Translating ASP.NET 4's HttpContext.Response.RedirectLocation  
 235:              httpContext.Response.Headers[HeaderNames.Location] = "http://www.example.com";
 236:              // Or
 237:              httpContext.Response.Redirect("http://www.example.com");
 238:   
 239:              // GetTypedHeaders extension method provides strongly typed access to many headers
 240:              var responseHeaders = httpContext.Response.GetTypedHeaders();
 241:   
 242:              // Translating ASP.NET 4's HttpContext.Response.CacheControl 
 243:              responseHeaders.CacheControl = new CacheControlHeaderValue
 244:              {
 245:                  MaxAge = new System.TimeSpan(365, 0, 0, 0)
 246:                  // Many more properties available 
 247:              };
 248:   
 249:              // If you use .Net 4.6+, Task.CompletedTask will be a bit faster
 250:              return Task.FromResult(0);
 251:          }
 252:          #endregion
 253:   
 254:          #region snippet_SetCookies
 255:          private Task SetCookies(object context)
 256:          {
 257:              var httpContext = (HttpContext)context;
 258:   
 259:              IResponseCookies responseCookies = httpContext.Response.Cookies;
 260:   
 261:              responseCookies.Append("cookie1name", "cookie1value");
 262:              responseCookies.Append("cookie2name", "cookie2value",
 263:                  new CookieOptions { Expires = System.DateTime.Now.AddDays(5), HttpOnly = true });
 264:   
 265:              // If you use .Net 4.6+, Task.CompletedTask will be a bit faster
 266:              return Task.FromResult(0); 
 267:          }
 268:          #endregion
 269:   
 270:          // You would normally use MVC to generate HTML like this.
 271:          private string GetResponseContent()
 272:          {
 273:              return @"
 274:  <!DOCTYPE html>
 275:  <html lang=""en"">
 276:  <head>
 277:      <title>index</title>
 278:  </head>
 279:  <body>
 280:  <form action=""form.context"" method=""post"">
 281:      <input type=""text"" name=""firstname"">
 282:      <input type=""text"" name=""lastname"">
 283:      <input type=""submit"" value=""Submit"">
 284:  </form> 
 285:  </body>
 286:  </html>
 287:  ";
 288:          }
 289:      }
 290:   
 291:      public static class HttpContextDemoMiddlewareExtensions
 292:      {
 293:          public static IApplicationBuilder UseHttpContextDemoMiddleware(this IApplicationBuilder builder)
 294:          {
 295:              return builder.UseMiddleware<HttpContextDemoMiddleware>();
 296:          }
 297:      }
 298:  }

Additional Resources





Comments ( )
<00>  <01>  <02>  <03>  <04>  <05>  <06>  <07>  <08>  <09>  <10>  <11>  <12>  <13>  <14>  <15>  <16>  <17>  <18>  <19>  <20>  <21>  <22>  <23
Link to this page: //www.vb-net.com/AspNet-DocAndSamples-2017/aspnetcore/migration/http-modules.htm
<SITEMAP>  <MVC>  <ASP>  <NET>  <DATA>  <KIOSK>  <FLEX>  <SQL>  <NOTES>  <LINUX>  <MONO>  <FREEWARE>  <DOCS>  <ENG>  <CHAT ME>  <ABOUT ME>  < THANKS ME>