Asp.Net ID がリクエストごとに 2 回作成および破棄される理由に関する質問の後、なぜこれが発生するのかを調査しました。実際には 1 回に 1 回作成さApplicationDbContext
れることがわかりましたが、Owin パイプラインを使用すると、Owin ミドルウェアは HttpRequest の終了後に 2 回作成されます。ApplicationDbContext
HttpRequest
このためApplicationDbContext
、ユーザーが 1 つのリンクをクリックすると、実際には が 2 回作成され、オブジェクトが ごとに 2 回作成されたような印象を受けますWebRequest
。
多くの調査の後、認証を使用せずにプレーンな MVC 5 プロジェクトを開始することにしました。NuGet から Owin ミドルウェアを追加した後、次のOwin Middleware
コンポーネントに作成しました。基本的に、HttpContext
辞書に偽のオブジェクトが存在するかどうかを確認し、存在しない場合は作成します。単純にするために、出力はデバッグ ウィンドウに書き込まれます。
[assembly: OwinStartupAttribute(typeof(MvcPlain.Startup))]
namespace MvcPlain
{
public class Startup {
public static int Counter;
public static string FakeKeyName;
public void Configuration(IAppBuilder app) {
app.Use(async (context, next) =>
{
Debug.WriteLine("Owin middleware entered => begin request");
FakeKeyName = "owinKey" + Counter.ToString();
var fakeKeyPresent = HttpContext.Current.Items.Contains(FakeKeyName);
Debug.WriteLine(string.Format("{0} key present in HttpContext?: {1}",
FakeKeyName, fakeKeyPresent));
if (!HttpContext.Current.Items.Contains(FakeKeyName))
{
Counter += 1;
HttpContext.Current.Items.Add(FakeKeyName, "someValue");
}
await next.Invoke();
Debug.WriteLine("Owin middleware exited => end request");
var keyStillPresent = HttpContext.Current.Items.Contains(FakeKeyName);
Debug.WriteLine(string.Format("{0} still present in HttpContext?: {1}",
FakeKeyName, keyStillPresent));
});
}
}
}
次に、これを のIndex
ActionMethod に追加してHomeController
、作成されたオブジェクトがまだ存在するかどうかを確認しました。
public ActionResult Index()
{
Debug.WriteLine("Index actionmethod called");
var fakeKeyPresent = HttpContext.Items.Contains(Startup.FakeKeyName);
Debug.WriteLine(string.Format("{0} key present in HttpContext?: {1}",
Startup.FakeKeyName, fakeKeyPresent));
return View();
}
実行すると、出力ウィンドウに次の出力が表示されます (わかりやすくするためにコメントを追加)。
--- home link clicked ---
Owin middleware entered => begin request
owinKey2 key present in HttpContext?: False
Index actionmethod called
owinKey2 key present in HttpContext?: True
Owin middleware exited => end request
owinKey2 key still present in HttpContext?: True
--- end of 'normal' request ---
Owin middleware entered => begin request
owinKey3 key present in HttpContext?: False
Owin middleware exited => end request
owinKey3 key still present in HttpContext?: True
では、なぜ、コメントの後にend of 'normal' request
、ミドルウェアが作成され、再度入力されるのでしょうか。誰にもアイデアや説明がありますか?
再現する手順:
- 認証なしで VS 2013 で新しい MVC 5 プロジェクトを開始する
Install-Package Microsoft.Owin.Host.SystemWeb
パッケージ マネージャーを使用して NuGet から Owin を追加する- 上記のようにスタートアップ クラスをプロジェクトに追加します。
Index
のActionMethod にコードを追加します。HomeController
- デバッグモードで F5 を押します
- スタート ページの [ホーム] リンクをクリックします。
- 出力 (または VS セットアップに応じて即時) ウィンドウで出力を確認します。