I'm creating an API server, i'm using a service to verify certain inputs, it's methods return ActionResult, this is so that i can either return a 403/404/200 result if the value is false. When my methods return this value it seems that the result.Value is always false?
I've attempted to just simply check if an ActionResult is status code 200 and skip the part, however there doesn't seem to be a way to do so (that seems correct)
Verification Method:
public async Task<ActionResult<bool>> CanUpdateUser(ClaimsPrincipal user, Organisation org, string userId)
{
if (org == null)
return StatusCode(404, ApiResponseConstants.OrganisationDoesntExist);
if (!org.UserIsMember(user))
return StatusCode(403, ApiResponseConstants.NotOrganisationMember);
if (!org.UserHasPermission(user, OrganisationPermissions.EditOrgUsers))
return StatusCode(403, ApiResponseConstants.NoPermission);
ResponseUser responseUser = await GetResponseUserAsync(org, userId);
if (responseUser == null)
return StatusCode(404, ApiResponseConstants.UserDoesntExist);
if (userId.Equals(org.Owner, StringComparison.OrdinalIgnoreCase))
return StatusCode(403, "Organisation owners cannot be updated");
string currentUserId = user.Claims.First(claim => claim.Type.Equals("sub")).Value;
return userId.Equals(currentUserId, StringComparison.OrdinalIgnoreCase) ? StatusCode(403, "Organisation users cannot update themselves") : Ok(true);
}
private static OkObjectResult Ok(object value)
{
return new OkObjectResult(value);
}
private static ObjectResult StatusCode(int statusCode, object value)
{
return new ObjectResult(value)
{
StatusCode = statusCode
};
}
Controller method using Verification method:
public async Task<ActionResult<bool>> CanUpdateUser(string organisation, string user, bool respond200 = true)
{
Organisation org = await _verificationService.VerifyOrganisation(organisation);
ActionResult<bool> result = await _canUserService.CanUpdateUser(User, org, user);
return respond200 ? Ok(result.Value) : result;
}
I would expect that result.Value == true when i do Ok(true) however it's false? If i put a debugger breakpoint in the StatusCode method the ObjectResult.Value == true so there's something strange going on here between the two methods?
EDIT:
As a note, i'm using .Net Core 2.2
I think your logic is wrong in this line of code
return userId.Equals(currentUserId, StringComparison.OrdinalIgnoreCase) ? StatusCode(403, "Organisation users cannot update themselves") : Ok(true);
Instead try to change to this to see if it work
return userId.Equals(currentUserId, StringComparison.OrdinalIgnoreCase) ? StatusCode(403, "Organisation users cannot update themselves") : true;
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