简体   繁体   English

OwinStartup 类中的 Configuration 方法如何以及何时被调用/执行?

[英]How and when does Configuration method in OwinStartup class is called/executed?

Before I ask my question I have already gone through the following posts:在我提出问题之前,我已经阅读了以下帖子:

  1. Can't get the OWIN Startup class to run in IIS Express after renaming ASP.NET project file and all the posts mentioned in the question. 重命名 ASP.NET 项目文件和问题中提到的所有帖子后,无法让 OWIN 启动类在 IIS Express 中运行
  2. OWIN Startup Detection OWIN启动检测
  3. OwinStartupAttribute required in web.config to correct Server Error #884 web.config 中需要 OwinStartupAttribute 来纠正服务器错误 #884
  4. OWIN Startup class not detected 未检测到 OWIN 启动类

Here is my project's folder layout:这是我项目的文件夹布局:

在此处输入图片说明
Currently there is no controller or view.目前没有控制器或视图。 Just the Owin Startup file.只是Owin Startup文件。


Startup.cs启动文件

using System;
using Microsoft.Owin;
using Owin;

[assembly: OwinStartup(typeof(Bootstrapper.Startup))]

namespace Bootstrapper
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.Run(async context =>
            {
                await context.Response.WriteAsync(GetTime() + " My First OWIN App");
            });
        }

        string GetTime()
        {
            return DateTime.Now.Millisecond.ToString();
        }
    }
}


Web.config网页配置

<appSettings>
    <add key="owin:AutomaticAppStartup" value="true" />
    <add key="owin:appStartup" value="Bootstrapper.Startup" />
    <add key="webpages:Version" value="2.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="PreserveLoginUrl" value="true" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>


I have the following reference in the Bootstrapper project:我在Bootstrapper项目中有以下参考:

  1. Microsoft.Owin微软.Owin
  2. Microsoft.Owin.Host.SystemWeb Microsoft.Owin.Host.SystemWeb
  3. Owin欧文
  4. System系统
  5. System.Core系统核心


UPDATE: Forgot to add the error message:更新:忘记添加错误信息:

在此处输入图片说明


Now,现在,

  1. WHY is it not working?为什么它不起作用?
  2. What is the step-by-step process of adding and using an Owin Startup class in a very basic project(like accessing Home/Index )?在一个非常基本的项目(如访问Home/Index )中添加和使用Owin Startup类的分步过程是什么?
  3. How and when does Configuration method in Owin Startup class is called/executed? Owin Startup类中的 Configuration 方法如何以及何时被调用/执行?


UPDATE: on 10-Dec-2016更新: 2016 年 12 月 10 日

Check the Project-Folder-Layout .检查Project-Folder-Layout In Bootstrapper project I have the following file:Bootstrapper项目中,我有以下文件:
IocConfig.cs配置文件

[assembly: PreApplicationStartMethod(typeof(IocConfig), "RegisterDependencies")]

namespace Bootstrapper
{
    public class IocConfig
    {
        public static void RegisterDependencies()
        {
            var builder = new ContainerBuilder();

            builder.RegisterControllers(typeof(MvcApplication).Assembly);
            builder.RegisterSource(new AnyConcreteTypeNotAlreadyRegisteredSource());
            builder.RegisterModule<AutofacWebTypesModule>();

            builder.RegisterType(typeof(MovieService)).As(typeof(IMovieService)).InstancePerRequest();
            builder.RegisterType(typeof(MovieRepository)).As(typeof(IMovieRepository)).InstancePerRequest();

            var container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }
    }
}

Now I want to execute IocConfig.RegisterDependencies() in OWIN Startup class.现在我想在OWIN Startup类中执行IocConfig.RegisterDependencies() I am doing using Bootstrapper in Startup at the top but, it is not working.我正在顶部的Startupusing Bootstrapper ,但它不起作用。 I mean I am unable to reference IocConfig in Startup .我的意思是我无法在Startup引用IocConfig How to resolve this?如何解决这个问题?

  1. Create an empty web application project创建一个空的 Web 应用程序项目
  2. Install the OWIN using NuGet ( install-package Microsoft.Owin.Host.SystemWeb )使用 NuGet ( install-package Microsoft.Owin.Host.SystemWeb ) 安装 OWIN
  3. Add an empty class into the project root called "Startup.cs"将一个空类添加到名为“Startup.cs”的项目根目录中

Here I will answer your third question.下面我来回答你的第三个问题。 The startup class is an entry point of OWIN and is being looked up automatically.启动类是 OWIN 的入口点,正在自动查找。 As stated in official docs:如官方文档所述:

Naming Convention: Katana looks for a class named Startup in namespace matching the assembly name or the global namespace.命名约定:Katana 在与程序集名称或全局命名空间匹配的命名空间中查找名为 Startup 的类。

Note, that you can also choose your own name of Startup class but you have to set this up using decorators or AppConfig.请注意,您也可以选择自己的 Startup 类名称,但必须使用装饰器或 AppConfig 进行设置。 As stated here: https://www.asp.net/aspnet/overview/owin-and-katana/owin-startup-class-detection如此处所述: https : //www.asp.net/aspnet/overview/owin-and-katana/owin-startup-class-detection

This is everything you need for a basic and working OWIN test:这是基本和有效的 OWIN 测试所需的一切:

using Owin;
using System;

namespace OwinTest
{
    public class Startup
    {
        public static void Configuration(IAppBuilder app)
        {
            app.Use(async (ctx, next) =>
            {
                await ctx.Response.WriteAsync(DateTime.Now.ToString() + " My First OWIN App");
            });
        }
    }
}

If you wish to use MVC (I guess by "Home/Index" you mean MVC), follow these steps:如果您希望使用 MVC (我猜“主页/索引”是指 MVC),请按照下列步骤操作:

  1. Install MVC NuGet ( install-package Microsoft.AspNet.Mvc ).安装 MVC NuGet( install-package Microsoft.AspNet.Mvc )。
  2. Add a "Controllers" folder into your project.将“Controllers”文件夹添加到您的项目中。
  3. Create a new empty controller under the new "Controlles" folder (right click -> add -> MVC 5 Controller - Empty) and name it "HomeController".在新的“Controlles”文件夹下创建一个新的空控制器(右键单击 -> 添加 -> MVC 5 Controller - Empty)并将其命名为“HomeController”。
  4. Create a view page under newly created "Views/Home" folder.在新创建的“Views/Home”文件夹下创建一个视图页面。 Right click -> add -> View.右键单击-> 添加-> 查看。 Name it "Index" and uncheck the "use layour page".将其命名为“索引”并取消选中“使用布局页面”。

Make the page inherit from WebViewPage.使页面继承自 WebViewPage。 It should all look like this:它应该看起来像这样:

@inherits System.Web.Mvc.WebViewPage
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div> 
        <h1>Owin Hello</h1>
    </div>
</body>
</html>
  1. Add a global.asax to set up routes.添加global.asax以设置路由。 Right click on the project -> add -> New Item -> Global Application Class.项目右键->添加->新建项目->全局应用类。

Add the routes definition to the Application_Start method:将路由定义添加到 Application_Start 方法:

protected void Application_Start(object sender, EventArgs e)
{
    RouteTable.Routes.MapRoute(name: "Default",
        url: "{controller}/{action}",
        defaults: new { controller = "Home", action = "Index" });
}
  1. Do not forget to comment out the above "..await ctx.Response.WriteAsync..." middleware.不要忘记注释掉上面的“..await ctx.Response.WriteAsync...”中间件。 It would interfere with the MVC otherwise.否则它会干扰 MVC。
  2. Run the project.运行项目。 Should be working.应该工作。

It's a little bit late, but I found the solution how to put OWIN Startup class in separate project.有点晚了,但我找到了如何将 OWIN Startup 类放在单独的项目中的解决方案。 Everything you did in your project is correct, you must only apply one change in the properties of your Bootstrapper project.您在项目中所做的一切都是正确的,您只能在 Bootstrapper 项目的属性中应用一项更改。 Right click on Bootstrapper project, enter properties, click Build tab and look for Output path.右键单击 Bootstrapper 项目,输入属性,单击构建选项卡并查找输出路径。 You should see standard output path bin\\debug\\ which means that your Bootstrapper dll will land in this folder.您应该会看到标准输出路径 bin\\debug\\,这意味着您的 Bootstrapper dll 将位于此文件夹中。 You must change this to the bin folder, where your whole web app is.您必须将其更改为整个 Web 应用程序所在的 bin 文件夹。

For example, I've created a simple solution with two projects, first is an empty web app, and the second is a library with an OWIN Startup class.例如,我创建了一个包含两个项目的简单解决方案,第一个是一个空的 Web 应用程序,第二个是一个带有 OWIN Startup 类的库。 In properties of the second project I've changed the output path to ..\\OwinTest.Web\\bin.在第二个项目的属性中,我将输出路径更改为 ..\\OwinTest.Web\\bin。 This will cause all dlls to land in one folder after the build.这将导致所有 dll 在构建后都位于一个文件夹中。 You can now run your app and OWIN Startup should work right.您现在可以运行您的应用程序,OWIN Startup 应该可以正常工作。

Below is the screen of properties settings of Bootstrapper project:下面是 Bootstrapper 项目的属性设置界面:

在此处输入图片说明

The WebApp class uses reflection to get a pointer to the Configuration(IAppBuilder) method then calls it. WebApp 类使用反射来获取指向 Configuration(IAppBuilder) 方法的指针,然后调用它。 If the class you provide as the generic type argument does not have a Configuration method with the expected arguments then you get an error at run time.如果您作为泛型类型参数提供的类没有包含预期参数的 Configuration 方法,那么您会在运行时收到错误消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM