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

Sta*_*ish 2 .net c# asp.net-web-api

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

protected override void Initialize(HttpControllerContext controllerContext)
{
// some logic
}
Run Code Online (Sandbox Code Playgroud)

有一个新的产品需求,我想根据一些标准在Initialize函数中返回客户端的响应.例如

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

}
Run Code Online (Sandbox Code Playgroud)

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

反正有没有在该函数内返回响应并停止执行?或者我必须重构现有代码以另一种方式执行此操作?

Bad*_*dri 5

这是一种完成你想要的东西的hacky方式.像这样抛出异常.

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

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

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

将过滤器应用于操作方法或控制器,甚至全局应用.

[MyAuthorize]
public HttpResponseMessage Get(int id)
{
     return null;
}
Run Code Online (Sandbox Code Playgroud)