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?
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With