1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

ASP.NET Core よ HttpContext.Current は、どこにいった?

Last updated at Posted at 2020-12-03

はじめに

ASP.NET では、System.Web.HttpContext.Current で System.Web.HttpContext のインスタンスを取得していました。

ASP.NET Core では、同等の Microsoft.AspNetCore.Http.HttpContext が使用され、コントローラーの継承元 Microsoft.AspNetCore.Mvc.ControllerBase のプロパティ HttpContext から、HttpContext のインスタンスが取得できるようになっています。

ビュー(*.cshtml) 側でも、Context プロパティから HttpContext を取得できます。

xxx.cshtml
@{
   var request = this.Context.Request;
   ...
}

これらの方法で HttpContext を取得できるので、困ることはほとんどないですが、Bot Framework SDK(ASP.NET Core 3.1 ベース) の Dialog で HttpContext を取得する際に困ったことがあるので、このような場合での解決方法を説明したいと思います。
もちろん、Bot Framework でなくても同様の手順で、HttpContext を取得できます。

HttpContextAccessor の依存性の注入とインスタンスの取得

依存性の注入で、IHttpContextAccessor のインスタンスを登録します。

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
     ...
     services.AddHttpContextAccessor();
     ...
}

あとは、コンストラクタ経由で、IHttpContextAccessor を取得するのみです。
IHttpContextAccessor.HttpContext で、HttpContext のインスタンスを取得できます。

MainDialog.cs

   public class MainDialog : ComponentDialog
   {
        private readonly IHttpContextAccessor _httpContextAccessor;
        protected readonly ILogger Logger;

        public MainDialog(IHttpContextAccessor httpContextAccessor, ILogger<MainDialog> logger)
            : base(nameof(MainDialog))
        {
            this._httpContextAccessor = httpContextAccessor;
            Logger = logger;

            ...
        }

        ...

        private void DoSomething()
        {
           var request = this._httpContextAccessor.HttpContext.Request;
           ...
        }
   ...
   }

参考サイト

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?