为了更好的测试工作与 Microsoft.Owin.Testing.TestServer, ,我发现这是全球性的。asax没有加载Owin TestServer。

所以,我试图移动我的全球。asax配置启动。cs如下,

public partial class Startup
{
    public void Configuration(IAppBuilder app)
    {
        // pasted Global.asax things start.
        GlobalConfiguration.Configuration.Formatters.Clear();

        var jsonSerializerSettings = new JsonSerializerSettings
        {
            PreserveReferencesHandling = PreserveReferencesHandling.Objects,
            ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
        };
        GlobalConfiguration.Configuration.Formatters.Add(new JsonMediaTypeFormatter() { SerializerSettings = jsonSerializerSettings });
        GlobalConfiguration.Configuration.Formatters.Add(new FormMultipartEncodedMediaTypeFormatter());

        AreaRegistration.RegisterAllAreas();
        GlobalConfiguration.Configure(WebApiConfig.Register);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
        // pasted Global.asax things end.

        ConfigureAuth(app);
    }
}

但是 TestServer 失败了 在配置的每个点初始化,例如 AreaRegistration.RegisterAllAreas, FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters), ,依此类推。..

最小可行迁移(使用TestServer成功测试)如下所示。

public partial class Startup
{
    public void Configuration(IAppBuilder app)
    {
        var config = new HttpConfiguration();
        config.Formatters.Clear();

        var jsonSerializerSettings = new JsonSerializerSettings
        {
            PreserveReferencesHandling = PreserveReferencesHandling.Objects,
            ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
        };
        config.Formatters.Add(new JsonMediaTypeFormatter() { SerializerSettings = jsonSerializerSettings });
        config.Formatters.Add(new FormMultipartEncodedMediaTypeFormatter());

        WebApiConfig.Register(config); // moved from GlobalConfiguration.Configure(WebApiConfig.Register)
        app.UseWebApi(config);
        ConfigureAuth(app);
    }
}

是否有无论如何将所有配置移动到启动。cs?

有帮助吗?

解决方案

正如你已经意识到的那样, OwinContext 被消耗 Startup.Configuration() 与传统的不同ASP.NET HttpContext 被消耗 MvcApplication.Application_Start().两者都使用不同的上下文管道。更具体地说,ASP.NET MVC仍然依赖 System.Web.dll 而ASP.NET Web API没有。

因此,根据您的代码,通常会在 MvcApplication.Application_Start() 不能在里面跑 Startup.Configuration():

  • AreaRegistration.RegisterAllAreas();:此方法依赖于 System.Web.dll.
  • RouteConfig.RegisterRoutes(RouteTable.Routes);: RouteCollection 是......的一部分 System.Web.dll.
  • GlobalConfiguration.Configure(WebApiConfig.Register):又来了, RouteCollectionWebApiConfig.Register() 是......的一部分 System.Web.dll.

用于OWIN上下文中的URL路由, AttributeRouting 被推荐。所以,而不是这个,尝试 config.MapHttpAttributeRoutes(); 这会给你很大的自由。

如果你还想跑 AreaRegistration.RegisterAllAreas(); 在OWIN上下文中, Startup.Configuration(), ,我最好建议导入 武士刀图书馆.这将OWIN与 System.Web.dll 这样你就可能实现你的目标。

HTH

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top