Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Terminate the execution of web api request in Initialize function

I am working on some Restful APIs in .net web api . All the API controllers that I am working on inherit from a base API controller. It has some logic in the Initialize function.

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

There is a new product requirement comes in and I want to return the response to the client in the Initialize function depending on some criteria. e.g.

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

}

however it seems like that the .net pipeline still moves on even I return the response already.

Is there anyway to return the response inside that function and stop the execution? Or I have to refactor the existing code to do it in another way?

like image 601
Stay Foolish Avatar asked Jan 24 '26 18:01

Stay Foolish


1 Answers

Here is a hacky way of accomplishing what you want. Throw an exception like so.

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

The cleaner way, assuming what you are trying to do is all about authorization is to create an authorization filter like so.

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;
    }
}

Apply the filter on the action method or controller or even globally.

[MyAuthorize]
public HttpResponseMessage Get(int id)
{
     return null;
}
like image 120
Badri Avatar answered Jan 27 '26 09:01

Badri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!