Подтвердить что ты не робот

Перенести Global.asax на Startup.cs

Для лучшего тестового задания с Microsoft.Owin.Testing.TestServer я обнаружил, что Global.asax не загружен Owin TestServer.

Итак, я пытаюсь переместить мои конфигурации Global.asax в Startup.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);
    }
}

В любом случае, чтобы переместить все конфигурации в Startup.cs?

4b9b3361

Ответ 1

Как вы уже знаете, 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): Опять же, RouteCollection внутри WebApiConfig.Register() является частью System.Web.dll.

Для маршрутизации URL-адресов в контексте OWIN рекомендуется AttributeRouting. Итак, вместо этого попробуйте config.MapHttpAttributeRoutes(); Это даст вам большую свободу.

Если вы все еще хотите запустить AreaRegistration.RegisterAllAreas(); в контексте OWIN, Startup.Configuration(), я бы рекомендовал импортировать библиотеку Katana. Это интегрирует OWIN с System.Web.dll, чтобы вы, вероятно, архивировали свою цель.

НТН