如何使用OWIN管道拦截404 Not Found

时间:2014-04-25 06:10:23

标签: asp.net-mvc owin asp.net-web-api2

我还有另外一个与Web-API和OWIN有关的问题。我是"玩"有了它,试图了解它,我想看看我是否可以在"回来的时候拦截404。来自网络api。

所以,我在启动时有以下内容..

app.Use(async (environment, next) =>
      {       
        Debug.WriteLine(environment.Request.Uri);
        await next();   
        Debug.WriteLine(environment.Response.StatusCode);
      });

  HttpConfiguration config = new HttpConfiguration();
  WebApiConfig.Register(config);
  app.UseWebApi(config);

然后我使用无效的URI执行GET(在浏览器中),以便获得404结果。我希望将此视为在Debug.WriteLine(environment.Response.StatusCode)中写出的状态代码

然而,我所看到的(在dev studio输出窗口中,因为我正在运行IIS express)是

http://localhost:55905/myresource
http://localhost:55905/myresource
200
200

我真的期待那里的404。

有谁知道为什么我们没有看到404回来?

我已查看了响应,无法在任何地方看到它。

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

/myresource是否是有效的webapi路线? 我认为(但我不确定)您的请求是由IIS直接忽略owin-pipeline来处理的。但我不知道为什么它以200响应。 你可以很容易地测试它。 假设您的代码和以下配置:

public static class WebApiConfig {
    public static void Register(HttpConfiguration config) {
        config.Routes.MapHttpRoute(
            name: "API Default",
            routeTemplate: "api/{controller}/{id}",
            defaults: new {id = RouteParameter.Optional}
            );
    }
}

稍微修改了你的Startup类:

app.Use(async (environment, next) => {
    Debug.WriteLine(environment.Request.Uri);

    environment.Response.OnSendingHeaders(_ => {
        var resp = ((IOwinResponse) _);
        Debug.WriteLine("Headers are send!: {0}", resp.StatusCode);
        resp.Headers.Add("X-MyTag", new[] {"Nice value!"});

    }, environment.Response);
    await next();
    Debug.WriteLine(environment.Response.StatusCode);
});

样本控制器:

public class ValuesController : ApiController {
    // GET api/<controller>
    public IEnumerable<string> Get() {
        return new string[] { "value1", "value2" };
    }
}

现在,OWIN管道应在EACH请求中返回自定义标头X-MyTag。 我使用Fiddler来检查我的请求。

http://localhost:13543/的请求在没有标题的情况下响应。所以它不是由owin管道服务的。 另一方面,http://localhost:13543/api/Values的请求以200和我的自定义标头响应。

http://localhost:13543/api/Values1的一个(无效)请求以404响应,包括我的自定义标题,你可以在输出控制台中看到这个404.