Using Breeze with IHttpActionResult

I came up with a solution for this as I was writing out my question on stackoverflow.com – I love when that happens!

I’m implementing measures on my controllers to prevent users from being able to access information that they shouldn’t have permission to.

I’m looking into having my controller methods return an IHttpActionResult. Consider this simplified example:

[HttpGet]
[BreezeQueryable]
public IHttpActionResult FindById(int id)
{
    // implementation of DoesUserHavePermission not relevant
    var canAccess = DoesUserHavePermission(id); 
    if (canAccess)
        return Ok(_uow.Repo.All().Where(r => r.Id == id).FirstOrDefault());
    else
        return NotFound();
}

On the client-side, it would look something like this:

return uow.Repo
    .findById(id)
    .then(function (results) {
	if (results[0] == undefined) {
    	    router.navigate(notFoundRoute);
	}
	else {
	    myEntity(results[0]);
	}
    })
    .fail(function (e) {
        // log an error
    });

This works great when you have a result, but if the controller returns a NotFound the call to findById actually fails because the call to the controller came back with a 404 status code.

Turns out a super easy way to handle this is to check the value of e.Status in the fail handler:

return uow.Repo
    .findById(id)
    .then(function (results) {
	if (results[0] == undefined) {
    	    router.navigate(notFoundRoute);
	}
	else {
	    myEntity(results[0]);
	}
    })
    .fail(function (e) {
        if (e.status = 404)
            router.navigate(notFoundRoute);
        else
            // log an error
    });

FYI that this is a SPA using BreezeJS and DurandalJS.

Leave a Reply

Your email address will not be published. Required fields are marked *