As I wrote in Self-host ASP.NET Web API and SignalR together, you can easily combine ASP.NET Web Api and OWIN. My Startup class contained at least the Configuration method:
1 2 3 4 5 6 | public void Configuration(IAppBuilder app) { HttpConfiguration config = new HttpConfiguration(); config.Routes.MapHttpRoute( "API Default" , "api/{controller}/{id}" , new { id = RouteParameter.Optional }); app.UseWebApi(config); } |
(Unfortunately) I am a well-behaved man. Therefore I ran the code analysis (aka FxCop). It returned the warning
1 | CA2000: Microsoft.Reliability: In method 'Startup.Configuration(IAppBuilder)', call System.IDisposable.Dispose on object 'config' before all references to it are out of scope. |
1 2 3 4 5 6 7 8 | public void Configuration(IAppBuilder app) { using (HttpConfiguration config = new HttpConfiguration()) { config.Routes.MapHttpRoute( "API Default" , "api/{controller}/{id}" , new { id = RouteParameter.Optional }); app.UseWebApi(config); } } |
When I finally put all together, I got only HTTP 500 Internal Server Error, without any further information. A lot of people suggest in such a case to debug the server, but also there no exception was thrown. It simply didn’t work. I slimmed down my coding until I removed the using statement. And then it worked again!
So it’s better to keep the original code and to add only a SuppressMessage attribute:
1 2 3 4 5 6 7 8 | [SuppressMessage( "Microsoft.Reliability" , "CA2000:Dispose objects before losing scope" , Justification = "HttpConfiguration must not be disposed, otherwise web api will not work" )] public void Configuration(IAppBuilder app) { HttpConfiguration config = new HttpConfiguration(); config.Routes.MapHttpRoute( "API Default" , "api/{controller}/{id}" , new { id = RouteParameter.Optional }); app.UseWebApi(config); } |
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.