为了更好地使用Microsoft.Owin.Testing.TestServer
进行测试工作,我发现Owin TestServer没有加载Global.asax。
因此,我尝试将我的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中?
Global.asax.cs
中的某些部分从Application_Start
移动到Startup.cs
,那么就应该没问题了。 - justinyoo