错误地异步调用异步方法

时间:2018-05-29 07:50:19

标签: c# asynchronous asp.net-web-api

我有以下异步方法:

[HttpGet]
[Route("api/SecurityRoles/AllowDeleteRole/{securityRoleId}")]
public async Task<IHttpActionResult> AllowDeleteRole(int securityRoleId)
{
    _systemLogger.LogInfo($"Method api/SecurityRoles/AllowDeleteRole (Get) called with securityRoleId: {securityRoleId}");

    var securityRolePermission =
            await _securityRolePermissionService.SecurityRolePermissionsCountBySecurityRoleId(securityRoleId);
    if (securityRolePermission != SecurityRoleDeleteResult.Success) return Ok(SecurityRoleDeleteResult.RolePermissionExists);

    var securityRolePageEntity =
            await  _securityRolePageEntityService.SecurityRolePageEntityCountBySecurityRoleId(securityRoleId);
    return Ok(securityRolePageEntity != SecurityRoleDeleteResult.Success ? SecurityRoleDeleteResult.RolePageEntityExists : SecurityRoleDeleteResult.Success);
    }

它在很多地方被使用,但对于这个实例,我需要使用非异步,所以我有以下代码首先包装它:

public async Task<SecurityRoleDeleteResult> AllowDeleteRole(int securityRoleId)
    {
        string url = $"{_housingDataSecurityConfiguration.HousingDataSecurityWebApiUrl}SecurityRoles/AllowDeleteRole/{securityRoleId}";
        var message =  _apiClientService.Retrieve<HttpResponseMessage>(url);

        if (message.StatusCode == HttpStatusCode.InternalServerError)
        {
            return SecurityRoleDeleteResult.ErrorOccurred;
        }

        int intResult = 0;
        var apiResult = await message.Content.ReadAsStringAsync();
        if (int.TryParse(apiResult, out intResult))
        {
            return (SecurityRoleDeleteResult)intResult;
        }
        else
        {
            return SecurityRoleDeleteResult.ErrorOccurred;
        }
    }
在被叫之前

public  SecurityRoleViewModel BuildViewModelForEdit(int id)
{

    var enableButton = false;
    _securityRoleService.AllowDeleteRole(id).ContinueWith(result =>
        {
            enableButton = (result.Result == SecurityRoleDeleteResult.Success) ? true : false;

    });

    SecurityRoleViewModel model = new SecurityRoleViewModel()
    {
        SecurityRole = _securityRoleService.SecurityRoleRetrieve(id),
        RolePermissions = _securityRoleService.SecurityRolePermissionsRetrieve(id),
        EnableDeleteButton = enableButton 
    };
    return model;
}

我的问题是,当我尝试在模型中设置EnableDeleteButton = enableButton时,它会在行上重新抛出以下错误:

enableButton = (result.Result == SecurityRoleDeleteResult.Success) ? true : false;
  

{&#34;将值3转换为类型&#39; System.Net.Http.HttpResponseMessage&#39;时出错。路径&#39;&#39;,第1行,第1位。&#34;}

3指的是我的SecurityRoleDeleteResult枚举中的一个枚举值。

1 个答案:

答案 0 :(得分:1)

AllowDeleteRole返回HttpResponseMessage。您传递到Lambda的result对象属于Task<IHttpActionResult>类型。因此,当你result.Result对象使用IHttpActionResult时,更具体地说,它出现HttpResponseMessage

这是您的问题的原因