在Initialize函数中终止web api请求的执行

时间:2013-10-19 02:47:13

标签: c# .net asp.net-web-api

我正在开发.net web api中的一些Restful API。我正在处理的所有API控制器都从基本API控制器继承。它在Initialize函数中有一些逻辑。

protected override void Initialize(HttpControllerContext controllerContext)
{
// some logic
}

有一个新的产品要求,我想根据一些标准在Initialize函数中将响应返回给客户端。 e.g。

 protected override void Initialize(HttpControllerContext controllerContext)
{
// some logic
   controllerContext.Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "error");

}
然而,即使我已经返回响应,似乎.net管道仍然继续运行。

无论如何都要在该函数内返回响应并停止执行?或者我必须重构现有代码以另一种方式执行它?

3 个答案:

答案 0 :(得分:5)

这是一种完成你想要的东西的hacky方式。抛出这样的例外。

protected override void Initialize(HttpControllerContext controllerContext)
{
       // some logic
       if(youhavetosend401)
           throw new HttpResponseException(HttpStatusCode.Unauthorized);
}

更清洁的方式,假设你要做的就是授权就是创建一个像这样的授权过滤器。

public class MyAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool IsAuthorized(HttpActionContext context)
    {
        // Do your stuff and determine if the request can proceed further or not
        // If not, return false
        return true;
    }
}

在操作方法或控制器上应用过滤器,甚至全局。

[MyAuthorize]
public HttpResponseMessage Get(int id)
{
     return null;
}

答案 1 :(得分:0)

使用HttpResponseException发送为Error创建的HttpResponseMessage。

protected override void Initialize(System.Web.Http.Controllers.HttpControllerContext controllerContext)
{ 
   //Your Logic
   throw new HttpResponseException(controllerContext.Request.CreateErrorResponse(System.Net.HttpStatusCode.Unauthorized, "error"));
   base.Initialize(controllerContext);
}

答案 2 :(得分:-1)

使用     Application.CompleteRequest() 它将触发EndRequest事件。