.Net Core ActionResult <bool>总是返回false?

时间:2019-09-07 09:41:55

标签: c# asp.net-core .net-core asp.net-core-mvc

我正在创建一个API服务器,我正在使用一种服务来验证某些输入,它的方法返回ActionResult,因此,如果该值为false,则我可以返回403/404/200的结果。当我的方法返回该值时,似乎result.Value始终为false?

我试图仅检查ActionResult是否为状态码200并跳过该部分,但是似乎没有办法(看来是正确的)

验证方法:

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

使用Verification方法的控制器方法:

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

我在做result.Value == true时会期望Ok(true)是错的吗?如果我将调试器断点放在StatusCode方法ObjectResult.Value == true中,那么这两种方法之间会发生奇怪的事情吗?

编辑:

请注意,我正在使用.Net Core 2.2

1 个答案:

答案 0 :(得分:0)

我认为您在这行代码中的逻辑是错误的

 return userId.Equals(currentUserId, StringComparison.OrdinalIgnoreCase) ? StatusCode(403, "Organisation users cannot update themselves") : Ok(true);

相反,请尝试更改为该功能以查看是否有效

 return userId.Equals(currentUserId, StringComparison.OrdinalIgnoreCase) ? StatusCode(403, "Organisation users cannot update themselves") : true;