本文介绍了该型Htt prequest结束之后为什么owin中间件创建第二次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个按为何 ApplicationDbContext 从Asp.Net的身份创建并每个请求我做了一些研究,为什么会发生这种事处理两次。我发现 ApplicationDbContext 的Htt prequest 但actualy创建一次使用Owin管道Owin中间件时,将要创建的Htt的prequest结束后的第二时间。

由于此的 ApplicationDbContext 的确是,当用户点击一个环节给IM pression该对象每<$创建两次,第二次创建C $ C>的WebRequest 。

在大量的调查研究,我决定不使用任何身份验证启动一个普通的MVC 5项目。从的NuGet添加Owin中间件后,我创建以下 Owin中间件组件。这意味着,如果一些假对象在的HttpContext 字典中基本检查,并创建之一,当它没有。输出写入调试窗口让事情变得简单。

  [汇编:OwinStartupAttribute(typeof运算(MvcPlain.Startup))]
命名空间MvcPlain
{
    公共类启动{
        公共静态INT计数;
        公共静态字符串FakeKeyName;        公共无效配置(IAppBuilder应用程序){
            app.Use(异步(背景下,下一个)=&GT;
            {
                的Debug.WriteLine(Owin中间件进入=&GT;开始申请);                FakeKeyName =owinKey+ Counter.ToString();
                VAR fakeKey present = HttpContext.Current.Items.Contains(FakeKeyName);                的Debug.WriteLine(的String.Format({0}键present在HttpContext的?:{1},
                                                        FakeKeyName,fakeKey present));                如果(!HttpContext.Current.Items.Contains(FakeKeyName))
                {
                    计数器+ = 1;
                    HttpContext.Current.Items.Add(FakeKeyNamesomeValue中);
                }                等待next.Invoke();                的Debug.WriteLine(Owin中间件退出= GT;结束请​​求);                VAR keyStill present = HttpContext.Current.Items.Contains(FakeKeyName);
                的Debug.WriteLine(的String.Format({0}仍present在HttpContext的?:{1},
                                                        FakeKeyName,keyStill present));
            });
        }
    }
}

随后已将此添加到首页的ActionMethod的的HomeController 来检查创建的对象仍然存在。

 公众的ActionResult指数()
{
    的Debug.WriteLine(索引actionmethod称为);
    VAR fakeKey present = HttpContext.Items.Contains(Startup.FakeKeyName);    的Debug.WriteLine(的String.Format({0}键present在HttpContext的?:{1},
                                            Startup.FakeKeyName,fakeKey present));    返回查看();
}

在运行输出窗口显示以下输出(为清楚起见加评论)

  ---首页链接点击---
Owin中间件进入=&GT;开始申请
owinKey2键present在HttpContext的?:假
指数actionmethod叫
owinKey2键present在HttpContext的?:真
Owin中间件退出=&GT;结束请求
owinKey2关键仍在美元的HttpContext p $ psent?:真
---正常的请求结束---
Owin中间件进入=&GT;开始申请
owinKey3键present在HttpContext的?:假
Owin中间件退出=&GT;结束请求
owinKey3关键仍在美元的HttpContext p $ psent?:真

那么,为什么,注释'正常'的要求结束后,是中间件创建并再次进入?任何人有任何想法或解释?

重现步骤:


  1. 在VS 2013中启动一个新的MVC项目5无需验证

  2. 从使用的NuGet添加Owin 安装封装Microsoft.Owin.Host.SystemWeb 的包管理器

  3. 启动类添加到项目如上图

  4. 的code添加到首页的ActionMethod的的HomeController

  5. 在调试模式下按下F5

  6. 单击起始页上的主页链接

  7. 观看输出的输出(或直接在你的VS设置取决于)窗口


解决方案

什么是最有可能发生在这里的是,有的实际上是两个的独立发生的请求。首先是为您的家庭/索引视图,第二是可能让这样的事情的favicon.ico A请求的浏览器。 (浏览器往往会自动地做到这一点。)

目前中间件的开始,插入一个调试助手,揭示了 context.Request.Path 的值以查看所请求的URL各一次。

After a question as per why the ApplicationDbContext from Asp.Net Identity is created and disposed twice per Request I did some research why this would happen. I found that the ApplicationDbContext is actualy created once per HttpRequest but when using the Owin pipeline the Owin Middleware will be created a second time after the HttpRequest has ended.

Because of this the ApplicationDbContext is indeed created for a second time when a user clicks one link giving the impression that the object is created twice per WebRequest.

After a lot of research I decided to start a plain MVC 5 project without using any authentication. After adding the Owin Middleware from NuGet I created to following Owin Middleware component. Which basically checks if some fake object exist in the HttpContext dictionary and creates one when it doesn't. The output is written to the debug window to keep things simple.

[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));
            });
        }
    }
}

Then added this to the Index ActionMethod of the HomeController to check if the created object still exists.

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();
}

When ran the output window shows the following output (added comment for clarity):

--- 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

So why, after the comment end of 'normal' request, is the middleware created and entered again? Anyone has any idea or explanation?

Steps to reproduce:

  1. Start a new MVC 5 project in VS 2013 without authentication
  2. Add Owin from NuGet using Install-Package Microsoft.Owin.Host.SystemWeb in the package manager
  3. Add a startup class to the project as shown above
  4. Add the code to the Index ActionMethod of the HomeController
  5. Hit F5 in debug mode
  6. Click on the 'Home' link on the start page
  7. Watch the output in the output (or immediate depending on your VS setup) window
解决方案

What's most likely happening here is that there are actually two separate requests happening. The first is for your Home/Index view, and the second is probably the browser making a request for something like favicon.ico. (Browsers tend to do that automatically.)

At the beginning of your middleware, insert a debugging helper that reveals the value of context.Request.Path to see what URL is being requested each time.

这篇关于该型Htt prequest结束之后为什么owin中间件创建第二次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 09:53