ASP.NET Core ara yazılıma HTTP işleyicileri ve modülleri geçirme

bu makalede, mevcut ASP.NET HTTP modüllerinin ve işleyicilerinin system. webserver 'den ASP.NET Core arasistemine nasıl geçirileceği gösterilmektedir.

Modüller ve işleyiciler yeniden ziyaret edildi

ASP.NET Core ara yazılıma devam etmeden önce, ilk olarak HTTP modüllerinin ve işleyicilerinin nasıl çalıştığını görelim:

Modüller Işleyicisi

İşleyiciler şunlardır:

  • IHttpHandler uygulayan sınıflar

  • Verilen bir dosya adına veya uzantıya sahip istekleri işlemek için kullanılır . rapor

  • Web.config ' de yapılandırıldı

Modüller şunlardır:

  • IHttpModule uygulayan sınıflar

  • Her istek için çağrılır

  • Kısa devre verebilir (bir isteğin daha fazla işlenmesini durdurabilirsiniz)

  • HTTP yanıtına ekleme yapabilir veya kendi kendine oluşturma

  • Web.config ' de yapılandırıldı

Modüllerin gelen istekleri işleme sırası şu şekilde belirlenir:

  1. ve gibi ASP.NET tarafından tetiklenen bir seri olaylar BeginRequest AuthenticateRequest . Tüm liste için, bkz System.Web.HttpApplication .. Her modül, bir veya daha fazla olay için bir işleyici oluşturabilir.

  2. Aynı olay için, Web.config yapılandırıldığı sıra.

Modüllere ek olarak, genel. asax. cs dosyanıza yaşam döngüsü olaylarının işleyicilerini ekleyebilirsiniz. Bu işleyiciler, yapılandırılan modüllerdeki işleyicilerden sonra çalışır.

İşleyiciler ve modüllerden ara yazılıma

Ara yazılım HTTP modülleriyle ve işleyicilerinden daha basittir:

  • Modüller, işleyiciler, Global. asax. cs, Web.config (IIS yapılandırması hariç) ve uygulama yaşam döngüsü kayboldu

  • Her iki modülün ve işleyicinin rolleri, ara yazılım tarafından ele alınmıştır

  • Ara yazılım Web.config yerine kod kullanarak yapılandırılır

  • Ardışık düzen dallandırma , yalnızca URL 'ye değil, istek üst bilgileri, sorgu dizeleri vb. gibi belirli bir ara yazılıma istek göndermenizi sağlar.
  • Ardışık düzen dallandırma , yalnızca URL 'ye değil, istek üst bilgileri, sorgu dizeleri vb. gibi belirli bir ara yazılıma istek göndermenizi sağlar.

Ara yazılım, modüllere çok benzer:

Ara yazılım ve modüller farklı bir sırayla işlenir:

Yetkilendirme ara yazılımı, yetkili olmayan bir kullanıcı için bir istek olan kısa devre dışı. MVC ara yazılımı tarafından dizin sayfasına yönelik bir isteğe izin verilir ve işlenir. Bir satış raporuna yönelik bir isteğe, özel bir rapor ara yazılımı tarafından izin verilir ve işlenir.

Yukarıdaki görüntüde, kimlik doğrulama ara, isteği kabul eden bir şekilde kabul edin.

Modül kodunu ara yazılıma geçirme

Var olan bir HTTP modülü şuna benzer olacaktır:

// ASP.NET 4 module

using System;
using System.Web;

namespace MyApp.Modules
{
    public class MyModule : IHttpModule
    {
        public void Dispose()
        {
        }

        public void Init(HttpApplication application)
        {
            application.BeginRequest += (new EventHandler(this.Application_BeginRequest));
            application.EndRequest += (new EventHandler(this.Application_EndRequest));
        }

        private void Application_BeginRequest(Object source, EventArgs e)
        {
            HttpContext context = ((HttpApplication)source).Context;

            // Do something with context near the beginning of request processing.
        }

        private void Application_EndRequest(Object source, EventArgs e)
        {
            HttpContext context = ((HttpApplication)source).Context;

            // Do something with context near the end of request processing.
        }
    }
}

ara yazılım sayfasında gösterildiği gibi, ASP.NET Core bir ara yazılım, bir Invoke HttpContext ve döndüren bir yöntemi ortaya çıkaran bir sınıftır Task . Yeni ara yazılım şu şekilde görünür:

// ASP.NET Core middleware

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;

namespace MyApp.Middleware
{
    public class MyMiddleware
    {
        private readonly RequestDelegate _next;

        public MyMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            // Do something with context near the beginning of request processing.

            await _next.Invoke(context);

            // Clean up.
        }
    }

    public static class MyMiddlewareExtensions
    {
        public static IApplicationBuilder UseMyMiddleware(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<MyMiddleware>();
        }
    }
}

Yukarıdaki ara yazılım şablonu, Ara yazılım yazmabölümündeki bölümden alınmıştır.

MyMiddlewareExtensions yardımcı sınıfı, kendi ara ortamınızı Startup sınıfınıza yapılandırmayı kolaylaştırır. UseMyMiddlewareYöntemi, ara yazılım sınıfınızı istek ardışık düzenine ekler. Ara yazılım tarafından istenen hizmetler, ara yazılım oluşturucusuna eklenir.

Modülünüzün bir isteği sonlandırabilir, örneğin Kullanıcı yetkilendirilmezse:

// ASP.NET 4 module that may terminate the request

private void Application_BeginRequest(Object source, EventArgs e)
{
    HttpContext context = ((HttpApplication)source).Context;

    // Do something with context near the beginning of request processing.

    if (TerminateRequest())
    {
        context.Response.End();
        return;
    }
}

Bir ara yazılım Invoke , işlem hattındaki sonraki ara yazılıma çağrı gerçekleştirerek bunu işler. Yanıt işlem hattı üzerinden geri geldiğinde, önceki middlewares hala çağrıldığı için, bu, isteği tamamen sonlandıramadığından emin olun.

// ASP.NET Core middleware that may terminate the request

public async Task Invoke(HttpContext context)
{
    // Do something with context near the beginning of request processing.

    if (!TerminateRequest())
        await _next.Invoke(context);

    // Clean up.
}

Modülünüzün işlevselliğini yeni ara yazılıma geçirdiğinizde, HttpContext sınıf ASP.NET Core içinde önemli ölçüde değiştiğinden kodunuzun derlenmediğini fark edebilirsiniz. daha sonra, yeni ASP.NET Core HttpContext 'e nasıl geçirebileceğiniz göreceksiniz.

Modül ekleme isteği ardışık düzenine geçiriliyor

HTTP modülleri, genellikle Web.config kullanarak istek ardışık düzenine eklenir:

<?xml version="1.0" encoding="utf-8"?>
<!--ASP.NET 4 web.config-->
<configuration>
  <system.webServer>
    <modules>
      <add name="MyModule" type="MyApp.Modules.MyModule"/>
    </modules>
  </system.webServer>
</configuration>

Yeni ara ortamınızı sınıfınızdaki istek ardışık düzenine ekleyerek bunu dönüştürün Startup :

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseBrowserLink();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }

    app.UseMyMiddleware();

    app.UseMyMiddlewareWithParams();

    var myMiddlewareOptions = Configuration.GetSection("MyMiddlewareOptionsSection").Get<MyMiddlewareOptions>();
    var myMiddlewareOptions2 = Configuration.GetSection("MyMiddlewareOptionsSection2").Get<MyMiddlewareOptions>();
    app.UseMyMiddlewareWithParams(myMiddlewareOptions);
    app.UseMyMiddlewareWithParams(myMiddlewareOptions2);

    app.UseMyTerminatingMiddleware();

    // Create branch to the MyHandlerMiddleware. 
    // All requests ending in .report will follow this branch.
    app.MapWhen(
        context => context.Request.Path.ToString().EndsWith(".report"),
        appBranch => {
            // ... optionally add more middleware to this branch
            appBranch.UseMyHandler();
        });

    app.MapWhen(
        context => context.Request.Path.ToString().EndsWith(".context"),
        appBranch => {
            appBranch.UseHttpContextDemoMiddleware();
        });

    app.UseStaticFiles();

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}

Yeni ara hattınızı eklediğiniz işlem hattının tam noktası, bir modül ( BeginRequest , EndRequest , vb.) olarak işlenen olaya ve Web.config içindeki modüller listenizde sıraya bağlıdır.

daha önce belirtildiği gibi, ASP.NET Core hiçbir uygulama yaşam döngüsü yoktur ve bu işlem, yaşam döngüsünün işlenme sırası modüller tarafından kullanılan siparişten farklıdır. Bu, sipariş kararlarınızı daha zor hale getirir.

Sıralama bir sorun haline gelirse, modülünüzü bağımsız olarak sıralanmış birden fazla ara yazılım bileşenine bölebilirsiniz.

İşleyici kodunu ara yazılıma geçirme

HTTP işleyicisi şuna benzer:

// ASP.NET 4 handler

using System.Web;

namespace MyApp.HttpHandlers
{
    public class MyHandler : IHttpHandler
    {
        public bool IsReusable { get { return true; } }

        public void ProcessRequest(HttpContext context)
        {
            string response = GenerateResponse(context);

            context.Response.ContentType = GetContentType();
            context.Response.Output.Write(response);
        }

        // ...

        private string GenerateResponse(HttpContext context)
        {
            string title = context.Request.QueryString["title"];
            return string.Format("Title of the report: {0}", title);
        }

        private string GetContentType()
        {
            return "text/plain";
        }
    }
}

ASP.NET Core projenizde bunu şuna benzer bir ara yazılıma çevirmeniz gerekir:

// ASP.NET Core middleware migrated from a handler

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using System.Threading.Tasks;

namespace MyApp.Middleware
{
    public class MyHandlerMiddleware
    {

        // Must have constructor with this signature, otherwise exception at run time
        public MyHandlerMiddleware(RequestDelegate next)
        {
            // This is an HTTP Handler, so no need to store next
        }

        public async Task Invoke(HttpContext context)
        {
            string response = GenerateResponse(context);

            context.Response.ContentType = GetContentType();
            await context.Response.WriteAsync(response);
        }

        // ...

        private string GenerateResponse(HttpContext context)
        {
            string title = context.Request.Query["title"];
            return string.Format("Title of the report: {0}", title);
        }

        private string GetContentType()
        {
            return "text/plain";
        }
    }

    public static class MyHandlerExtensions
    {
        public static IApplicationBuilder UseMyHandler(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<MyHandlerMiddleware>();
        }
    }
}

Bu ara yazılım, modüllerle ilgili olan ara yazılıma çok benzer. Gerçek fark, burada hiçbir çağrı olmadığı için geçerlidir _next.Invoke(context) . Bu anlamlı hale gelir, çünkü işleyici istek ardışık düzeninin sonunda olduğundan, çağırmak için bir sonraki ara yazılım olmayacaktır.

İşleyici ekleme isteği ardışık düzenine geçiriliyor

HTTP işleyicisini yapılandırma Web.config yapılır ve şuna benzer:

<?xml version="1.0" encoding="utf-8"?>
<!--ASP.NET 4 web.config-->
<configuration>
  <system.webServer>
    <handlers>
      <add name="MyHandler" verb="*" path="*.report" type="MyApp.HttpHandlers.MyHandler" resourceType="Unspecified" preCondition="integratedMode"/>
    </handlers>
  </system.webServer>
</configuration>

Bu, yeni işleyici ara ortamınızı sınıfınızdaki istek ardışık düzenine ekleyerek Startup , modüllerden dönüştürülen ara yazılıma benzer şekilde dönüştürebilirsiniz. Bu yaklaşımla ilgili sorun, tüm istekleri yeni işleyici ara yazılıma göndermektir. Ancak, yalnızca belirli bir uzantıya sahip isteklerin ara yazılıma ulaşmasını istiyorsunuz. Bu, size HTTP işleyiciniz ile aynı işlevselliği sağlar.

Bir çözüm, genişletme yöntemi kullanılarak belirli bir uzantıya sahip istekler için ardışık düzeni dallandırmayı kullanmaktır MapWhen . Bunu, Configure diğer ara yazılımı eklediğiniz yöntemde yapabilirsiniz:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseBrowserLink();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }

    app.UseMyMiddleware();

    app.UseMyMiddlewareWithParams();

    var myMiddlewareOptions = Configuration.GetSection("MyMiddlewareOptionsSection").Get<MyMiddlewareOptions>();
    var myMiddlewareOptions2 = Configuration.GetSection("MyMiddlewareOptionsSection2").Get<MyMiddlewareOptions>();
    app.UseMyMiddlewareWithParams(myMiddlewareOptions);
    app.UseMyMiddlewareWithParams(myMiddlewareOptions2);

    app.UseMyTerminatingMiddleware();

    // Create branch to the MyHandlerMiddleware. 
    // All requests ending in .report will follow this branch.
    app.MapWhen(
        context => context.Request.Path.ToString().EndsWith(".report"),
        appBranch => {
            // ... optionally add more middleware to this branch
            appBranch.UseMyHandler();
        });

    app.MapWhen(
        context => context.Request.Path.ToString().EndsWith(".context"),
        appBranch => {
            appBranch.UseHttpContextDemoMiddleware();
        });

    app.UseStaticFiles();

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}

MapWhen Şu parametreleri alır:

  1. HttpContext' İ alan ve true isteğin dala gitmesi gerekiyorsa, döndüren bir lambda. Bu, yalnızca uzantısına göre değil, istek üst bilgileri, sorgu dizesi parametreleri vb. için istekleri dallayabileceğiniz anlamına gelir.

  2. IApplicationBuilderVe dalı için tüm ara yazılımı ekleyen bir lambda. Bu, işleyici ara uçınızın önünde dala ek ara yazılım ekleyebileceğiniz anlamına gelir.

Dal tüm isteklerde çağrılmadan önce işlem hattına eklenen ara yazılım; dalın üzerinde hiçbir etkisi olmaz.

Seçenekler modelini kullanarak ara yazılım seçeneklerini yükleme

Bazı modüller ve işleyiciler Web.config depolanan yapılandırma seçeneklerine sahiptir. ancak ASP.NET Core Web.config yerine yeni bir yapılandırma modeli kullanılır.

Yeni yapılandırma sistemi , bunu çözümlemek için size bu seçenekleri sunar:

  1. Ara yazılım seçeneklerinizi barındıracak bir sınıf oluşturun, örneğin:

    public class MyMiddlewareOptions
    {
        public string Param1 { get; set; }
        public string Param2 { get; set; }
    }
    
  2. Seçenek değerlerini depolama

    Yapılandırma sistemi istediğiniz her yerde seçenek değerlerini depolamanıza olanak tanır. Ancak, çoğu site appsettings.json tarafından kullanılır, bu yaklaşım şu şekilde ele alacağız:

    {
      "MyMiddlewareOptionsSection": {
        "Param1": "Param1Value",
        "Param2": "Param2Value"
      }
    }
    

    Burada MyMiddlewareOptionsSection bir bölüm adıdır. Seçenek sınıfınızın adıyla aynı olması gerekmez.

  3. Seçenek değerlerini Options sınıfıyla ilişkilendirin

    seçenekler stili, seçenek türünü (gibi MyMiddlewareOptions ) gerçek seçeneklere sahip bir nesneyle ilişkilendirmek için ASP.NET Core bağımlılık ekleme çerçevesini kullanır MyMiddlewareOptions .

    Sınıfınızı güncelleştirin Startup :

    1. Kullanıyorsanız appsettings.json , oluşturucunun yapılandırma oluşturucusuna ekleyin Startup :

      public Startup(IHostingEnvironment env)
      {
          var builder = new ConfigurationBuilder()
              .SetBasePath(env.ContentRootPath)
              .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
              .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
              .AddEnvironmentVariables();
          Configuration = builder.Build();
      }
      
    2. Seçenekler hizmetini yapılandırın:

      public void ConfigureServices(IServiceCollection services)
      {
          // Setup options service
          services.AddOptions();
      
          // Load options from section "MyMiddlewareOptionsSection"
          services.Configure<MyMiddlewareOptions>(
              Configuration.GetSection("MyMiddlewareOptionsSection"));
      
          // Add framework services.
          services.AddMvc();
      }
      
    3. Seçeneklerinizi seçenekler sınıfınız ile ilişkilendirin:

      public void ConfigureServices(IServiceCollection services)
      {
          // Setup options service
          services.AddOptions();
      
          // Load options from section "MyMiddlewareOptionsSection"
          services.Configure<MyMiddlewareOptions>(
              Configuration.GetSection("MyMiddlewareOptionsSection"));
      
          // Add framework services.
          services.AddMvc();
      }
      
  4. Seçenekleri, ara yazılım yapıcısına ekleyin. Bu, ekleme seçeneklerine bir denetleyiciye benzer.

    public class MyMiddlewareWithParams
    {
        private readonly RequestDelegate _next;
        private readonly MyMiddlewareOptions _myMiddlewareOptions;
    
        public MyMiddlewareWithParams(RequestDelegate next,
            IOptions<MyMiddlewareOptions> optionsAccessor)
        {
            _next = next;
            _myMiddlewareOptions = optionsAccessor.Value;
        }
    
        public async Task Invoke(HttpContext context)
        {
            // Do something with context near the beginning of request processing
            // using configuration in _myMiddlewareOptions
    
            await _next.Invoke(context);
    
            // Do something with context near the end of request processing
            // using configuration in _myMiddlewareOptions
        }
    }
    

    Ara ortamınızı bağımlılık ekleme ' ye ekleyen Useara yazılım genişletme yöntemi IApplicationBuilder .

    Bu nesnelerle sınırlı değildir IOptions . Bu şekilde, ara yazılım için gereken diğer tüm nesneler bu şekilde eklenebilir.

Doğrudan ekleme yoluyla ara yazılım seçeneklerini yükleme

Seçenekler deseninin, seçenek değerleri ve tüketicileri arasında gevşek bir bağlantısını oluşturduğunu avantajı vardır. Bir seçenek sınıfını gerçek seçenek değerleriyle ilişkilendirdikten sonra, diğer herhangi bir sınıf, bağımlılık ekleme çerçevesi aracılığıyla seçeneklere erişim alabilir. Seçenek değerlerini geçirmeye gerek yoktur.

Bu, farklı seçeneklerle aynı ara yazılımı iki kez kullanmak istiyorsanız bu seçeneği keser. Örneğin farklı dallarda farklı rollere izin veren bir yetkilendirme ara yazılımı. İki farklı seçenek nesnesini tek bir seçenek sınıfıyla ilişkilendiremezsiniz.

Çözüm, seçenek nesnelerini sınıfınıza gerçek seçenek değerleriyle almak Startup ve bunları doğrudan ara yazılım örneğine iletmektir.

  1. İkinci bir anahtar Ekle appsettings.json

    Dosyaya ikinci bir seçenek kümesi eklemek için appsettings.json , benzersiz bir şekilde tanımlamak için yeni bir anahtar kullanın:

    {
      "MyMiddlewareOptionsSection2": {
        "Param1": "Param1Value2",
        "Param2": "Param2Value2"
      },
      "MyMiddlewareOptionsSection": {
        "Param1": "Param1Value",
        "Param2": "Param2Value"
      }
    }
    
  2. Seçenek değerlerini alın ve bunları ara yazılıma geçirin. Use...Genişletme yöntemi (ara yazılımını işlem hattına ekleyen), seçenek değerlerinde geçirilecek mantıksal bir yerdir:

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();
    
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseBrowserLink();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }
    
        app.UseMyMiddleware();
    
        app.UseMyMiddlewareWithParams();
    
        var myMiddlewareOptions = Configuration.GetSection("MyMiddlewareOptionsSection").Get<MyMiddlewareOptions>();
        var myMiddlewareOptions2 = Configuration.GetSection("MyMiddlewareOptionsSection2").Get<MyMiddlewareOptions>();
        app.UseMyMiddlewareWithParams(myMiddlewareOptions);
        app.UseMyMiddlewareWithParams(myMiddlewareOptions2);
    
        app.UseMyTerminatingMiddleware();
    
        // Create branch to the MyHandlerMiddleware. 
        // All requests ending in .report will follow this branch.
        app.MapWhen(
            context => context.Request.Path.ToString().EndsWith(".report"),
            appBranch => {
                // ... optionally add more middleware to this branch
                appBranch.UseMyHandler();
            });
    
        app.MapWhen(
            context => context.Request.Path.ToString().EndsWith(".context"),
            appBranch => {
                appBranch.UseHttpContextDemoMiddleware();
            });
    
        app.UseStaticFiles();
    
        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }
    
  3. Bir seçenek parametresi almak için ara yazılımı etkinleştirin. Uzantı yönteminin bir aşırı yüklemesini sağlayın Use... (Options parametresini alır ve ' ye geçirir UseMiddleware ). UseMiddlewareParametreler ile çağrıldığında, ara yazılım nesnesini örnekleyen zaman, parametreleri ara yazılım yapıcısına geçirir.

    public static class MyMiddlewareWithParamsExtensions
    {
        public static IApplicationBuilder UseMyMiddlewareWithParams(
            this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<MyMiddlewareWithParams>();
        }
    
        public static IApplicationBuilder UseMyMiddlewareWithParams(
            this IApplicationBuilder builder, MyMiddlewareOptions myMiddlewareOptions)
        {
            return builder.UseMiddleware<MyMiddlewareWithParams>(
                new OptionsWrapper<MyMiddlewareOptions>(myMiddlewareOptions));
        }
    }
    

    Bunun nesne içindeki Options nesnesini nasıl saryacağını aklınızda edin OptionsWrapper . Bu IOptions , ara yazılım oluşturucusu tarafından beklendiği şekilde uygulanır.

Yeni HttpContext 'e geçiş

Daha önce, Invoke Ara ortamınızdaki yöntemin türünde bir parametre alıp aldıklarını gördünüz HttpContext :

public async Task Invoke(HttpContext context)

HttpContextASP.NET Core içinde önemli ölçüde değişmiştir. Bu bölümde, en yaygın olarak kullanılan System. Web. HttpContext özelliklerinin yeni sürümüne nasıl çevrilebileceğini gösterir Microsoft.AspNetCore.Http.HttpContext .

HttpContext

HttpContext. Items şu şekilde çevirir:

IDictionary<object, object> items = httpContext.Items;

Benzersiz istek KIMLIĞI (System. Web. HttpContext karşılığı)

Size her istek için benzersiz bir kimlik verir. Günlüklerinizi eklemek çok yararlı.

string requestId = httpContext.TraceIdentifier;

HttpContext. Request

HttpContext. Request. HttpMethod şu şekilde çevirir:

string httpMethod = httpContext.Request.Method;

HttpContext. Request. QueryString şu şekilde çevirir:

IQueryCollection queryParameters = httpContext.Request.Query;

// If no query parameter "key" used, values will have 0 items
// If single value used for a key (...?key=v1), values will have 1 item ("v1")
// If key has multiple values (...?key=v1&key=v2), values will have 2 items ("v1" and "v2")
IList<string> values = queryParameters["key"];

// If no query parameter "key" used, value will be ""
// If single value used for a key (...?key=v1), value will be "v1"
// If key has multiple values (...?key=v1&key=v2), value will be "v1,v2"
string value = queryParameters["key"].ToString();

HttpContext. Request. URL ve HttpContext. Request. RawUrl şu şekilde çeviri yapar:

// using Microsoft.AspNetCore.Http.Extensions;
var url = httpContext.Request.GetDisplayUrl();

HttpContext. Request. IsSecureConnection şu şekilde çevirir:

var isSecureConnection = httpContext.Request.IsHttps;

HttpContext. Request. UserHostAddress şu şekilde çevirir:

var userHostAddress = httpContext.Connection.RemoteIpAddress?.ToString();

HttpContext. Request. Cookie , şu şekilde çevirir:

IRequestCookieCollection cookies = httpContext.Request.Cookies;
string unknownCookieValue = cookies["unknownCookie"]; // will be null (no exception)
string knownCookieValue = cookies["cookie1name"];     // will be actual value

HttpContext. Request. RequestContext. RouteData şu şekilde çevirir:

var routeValue = httpContext.GetRouteValue("key");

HttpContext. Request. Headers şu şekilde çevirir:

// using Microsoft.AspNetCore.Http.Headers;
// using Microsoft.Net.Http.Headers;

IHeaderDictionary headersDictionary = httpContext.Request.Headers;

// GetTypedHeaders extension method provides strongly typed access to many headers
var requestHeaders = httpContext.Request.GetTypedHeaders();
CacheControlHeaderValue cacheControlHeaderValue = requestHeaders.CacheControl;

// For unknown header, unknownheaderValues has zero items and unknownheaderValue is ""
IList<string> unknownheaderValues = headersDictionary["unknownheader"];
string unknownheaderValue = headersDictionary["unknownheader"].ToString();

// For known header, knownheaderValues has 1 item and knownheaderValue is the value
IList<string> knownheaderValues = headersDictionary[HeaderNames.AcceptLanguage];
string knownheaderValue = headersDictionary[HeaderNames.AcceptLanguage].ToString();

HttpContext. Request. UserAgent şu şekilde çevirir:

string userAgent = headersDictionary[HeaderNames.UserAgent].ToString();

HttpContext. Request. Urlbaşvuran şu şekilde çevirir:

string urlReferrer = headersDictionary[HeaderNames.Referer].ToString();

HttpContext. Request. ContentType şuna çevirir:

// using Microsoft.Net.Http.Headers;

MediaTypeHeaderValue mediaHeaderValue = requestHeaders.ContentType;
string contentType = mediaHeaderValue?.MediaType.ToString();   // ex. application/x-www-form-urlencoded
string contentMainType = mediaHeaderValue?.Type.ToString();    // ex. application
string contentSubType = mediaHeaderValue?.SubType.ToString();  // ex. x-www-form-urlencoded

System.Text.Encoding requestEncoding = mediaHeaderValue?.Encoding;

HttpContext. Request. form şu şekilde çevirir:

if (httpContext.Request.HasFormContentType)
{
    IFormCollection form;

    form = httpContext.Request.Form; // sync
    // Or
    form = await httpContext.Request.ReadFormAsync(); // async

    string firstName = form["firstname"];
    string lastName = form["lastname"];
}

Uyarı

Form değerlerini yalnızca içerik alt türü x-www-form-urlencoded veya form-Data ise okuyun.

HttpContext. Request. InputStream şu şekilde çevirir:

string inputBody;
using (var reader = new System.IO.StreamReader(
    httpContext.Request.Body, System.Text.Encoding.UTF8))
{
    inputBody = reader.ReadToEnd();
}

Uyarı

Bu kodu yalnızca bir işlem hattının sonundaki bir işleyici türü ara yazılım içinde kullanın.

Ham gövdeyi, her istek için yukarıda yalnızca bir kez gösterildiği gibi okuyabilirsiniz. İlk okuduktan sonra gövde okumayı deneyen ara yazılım boş bir gövde okur.

Bu, bir arabelleğin yapıldığı için daha önce gösterildiği gibi bir formu okumak için uygulanmaz.

HttpContext. Response

HttpContext. Response. Status ve HttpContext. Response. StatusDescription şu şekilde çeviri yapar:

// using Microsoft.AspNetCore.Http;
httpContext.Response.StatusCode = StatusCodes.Status200OK;

HttpContext. Response. Contentenkodlamaya ve HttpContext. Response. ContentType şuna çevir:

// using Microsoft.Net.Http.Headers;
var mediaType = new MediaTypeHeaderValue("application/json");
mediaType.Encoding = System.Text.Encoding.UTF8;
httpContext.Response.ContentType = mediaType.ToString();

Yalnızca HttpContext. Response. ContentType şuna çevrilir:

httpContext.Response.ContentType = "text/html";

HttpContext. Response. Output şu şekilde çevirir:

string responseContent = GetResponseContent();
await httpContext.Response.WriteAsync(responseContent);

HttpContext. Response. TransmitFile

Bir dosya sunma konusunda açıklanmaktadır ASP.NET Core içindeki istek özellikleri .

HttpContext. Response. Headers

Yanıt üst bilgilerinin gönderilmesi, yanıt gövdesine herhangi bir şey yazıldıktan sonra ayarlandıklarında, gönderilmeyeceği için karmaşıktır.

Çözüm, yanıt başladıktan sonra hemen çağrılacak bir geri çağırma yöntemi ayarlamak olacaktır. Bu en iyi işlem, Invoke Ara ortamınızdaki yöntemin başlangıcında yapılır. Yanıt başlıklarınızı ayarlayan bu geri çağırma yöntemidir.

Aşağıdaki kod, adlı bir geri çağırma yöntemi ayarlar SetHeaders :

public async Task Invoke(HttpContext httpContext)
{
    // ...
    httpContext.Response.OnStarting(SetHeaders, state: httpContext);

SetHeadersGeri çağırma yöntemi şöyle görünür:

// using Microsoft.AspNet.Http.Headers;
// using Microsoft.Net.Http.Headers;

private Task SetHeaders(object context)
{
    var httpContext = (HttpContext)context;

    // Set header with single value
    httpContext.Response.Headers["ResponseHeaderName"] = "headerValue";

    // Set header with multiple values
    string[] responseHeaderValues = new string[] { "headerValue1", "headerValue1" };
    httpContext.Response.Headers["ResponseHeaderName"] = responseHeaderValues;

    // Translating ASP.NET 4's HttpContext.Response.RedirectLocation  
    httpContext.Response.Headers[HeaderNames.Location] = "http://www.example.com";
    // Or
    httpContext.Response.Redirect("http://www.example.com");

    // GetTypedHeaders extension method provides strongly typed access to many headers
    var responseHeaders = httpContext.Response.GetTypedHeaders();

    // Translating ASP.NET 4's HttpContext.Response.CacheControl 
    responseHeaders.CacheControl = new CacheControlHeaderValue
    {
        MaxAge = new System.TimeSpan(365, 0, 0, 0)
        // Many more properties available 
    };

    // If you use .NET Framework 4.6+, Task.CompletedTask will be a bit faster
    return Task.FromResult(0);
}

HttpContext. Response. Cookie malar

Cookies, bir set- Cookie Response üst bilgisinde tarayıcıya seyahat ediyor. Sonuç olarak, ' cookie ın gönderilmesi yanıt üst bilgilerini göndermek için kullanılan geri çağırma işlemini gerektirir:

public async Task Invoke(HttpContext httpContext)
{
    // ...
    httpContext.Response.OnStarting(SetCookies, state: httpContext);
    httpContext.Response.OnStarting(SetHeaders, state: httpContext);

SetCookiesGeri çağırma yöntemi aşağıdaki gibi görünür:

private Task SetCookies(object context)
{
    var httpContext = (HttpContext)context;

    IResponseCookies responseCookies = httpContext.Response.Cookies;

    responseCookies.Append("cookie1name", "cookie1value");
    responseCookies.Append("cookie2name", "cookie2value",
        new CookieOptions { Expires = System.DateTime.Now.AddDays(5), HttpOnly = true });

    // If you use .NET Framework 4.6+, Task.CompletedTask will be a bit faster
    return Task.FromResult(0); 
}

Ek kaynaklar