Chr*_*her 5 asp.net routes url-routing owin asp.net-web-api2
我有一个相对简单的WebApi网站,其中包含几个控制器,它们在OWIN中以AutoFac作为DI容器运行。
该站点仅使用属性路由进行设置,但即使遇到无效路由也始终返回200 OK响应。我们也有一些过滤器和一个运行的静态文件服务器,但是我已经注释掉了启动文件中的所有代码(所有IAppBuilder调用,甚至是HttpConfiguration的创建),但是我们仍然可以做到这一点。在IIS和IIS Express中都会发生这种情况。
我也曾尝试在其中添加默认路由,但看到的行为相同。
我已经读了一些书,并且了解到我可以在流水线中编写某种钩子,或者编写一个具有捕获所有路由和返回404的动作的控制器,但是感觉好像没有必要。
这是默认行为吗?
我已经看过这个答案了,但我们没有global.asax:ASP.NET Web Api在应返回404时返回200 OK
请参见下面的精简代码,该代码仍能说明问题
启动文件
[assembly: OwinStartup(typeof(Startup))]
namespace Api.blah
{
using Owin;
public class Startup
{
public void Configuration(IAppBuilder app)
{
var config = new HttpConfiguration();
var container = this.GetAutofacContainer(config);
config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
config.MapHttpAttributeRoutes();
app.UseWebApi(config);
}
private IContainer GetAutofacContainer(HttpConfiguration config)
{
ContainerBuilder containerBuilder = new ContainerBuilder();
containerBuilder.RegisterApiControllers(Assembly.GetExecutingAssembly());
return containerBuilder.Build();
}
}
}
Run Code Online (Sandbox Code Playgroud)
HealthController.cs
namespace Api.blah.Controller
{
[RoutePrefix("api/health")]
public class HealthController : ApiController
{
public HealthController()
{
}
[HttpGet]
[Route]
public HealthResponse Get()
{
return new HealthResponse { Alive = true, Healthy = true };
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果我访问的不是api / health路由(例如http:// localhost:1333 / zz),那么我得到200。原始代码比这大,但是如上所述,我已经大大减少了它,并且同样的行为仍然存在
如果您的 web.config 包含 StaticFileModule,则可能会发生此问题
<handlers>
<!-- Remove all handlers -->
<clear />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
<add name="StaticFile" path="*" verb="*" modules="StaticFileModule" resourceType="Unspecified" requireAccess="Read" />
</handlers>
Run Code Online (Sandbox Code Playgroud)
如果您需要静态文件,可以使用以下路径解决此问题:
<add name="StaticFile" path="/staticfiles" verb="*" modules="StaticFileModule" resourceType="Unspecified" requireAccess="Read" />
Run Code Online (Sandbox Code Playgroud)