Skip to main content
 首页 » 编程设计

c#之无法将类型 'Microsoft.Azure.Documents.Document' 隐式转换为 'System.Web.Http.IHttpActionResult' 。

2024年02月25日31zhengyun_ustc

我有以下 webapi

 public class TenantController : ApiController 
    { 
        private static DocumentClient client; 
 
        public TenantController() 
        { 
            client = new DocumentClient(new Uri(ConfigurationManager.AppSettings["endpoint"]), ConfigurationManager.AppSettings["authKey"]); 
        } 
 
        public async Task<List<Tenant>> GetTenants() 
        { 
            return await  DocumentDBRepository<List<Tenant>>.GetItemsAsync(d => d. != null); 
        } 
 
        public async Task<IHttpActionResult> GetTenant(string id)  
        { 
            Tenant tenant= await DocumentDBRepository<Tenant>.GetItemAsync(id); 
 
            if (tenant == null) 
            { 
                return NotFound(); 
            } 
            return Ok(tenant); 
        } 
 
        public async Task<IHttpActionResult>  PutTenant(string id, Tenant tenant) 
        { 
            if (!ModelState.IsValid) 
            { 
                return BadRequest(ModelState); 
            } 
            if (id != tenant.TenantId) 
            { 
                return BadRequest(); 
            } 
 
            await DocumentDBRepository<Tenant>.CreateItemAsync(tenant); 
 
            return StatusCode(HttpStatusCode.NoContent);  
        } 
 
        public async Task<IHttpActionResult> PostTenant(string id, Tenant tenant) 
        { 
            if (!ModelState.IsValid) 
            { 
                return BadRequest(ModelState); 
            } 
            return await DocumentDBRepository<Tenant>.UpdateItemAsync(id, tenant); 
        } 
 
        public async Task<IHttpActionResult> DeleteTenant(string id) 
        { 
            await DocumentDBRepository<Tenant>.DeleteItemAsync(id); 
            return Ok(id); 
        } 
    } 

但我对后租户方法有疑问

Cannot implicitly convert type 'Microsoft.Azure.Documents.Document' to 'System.Web.Http.IHttpActionResult'.

是的,我知道类型转换是如何工作的,但我想知道我是否在这里做错了什么?

请您参考如下方法:

你没有告诉我们错误发生在哪一行,但我猜应该是在这里

    public async Task<IHttpActionResult> PostTenant(string id, Tenant tenant) 
    { 
        if (!ModelState.IsValid) 
        { 
            return BadRequest(ModelState); 
        } 
        /// Error is here 
        return await DocumentDBRepository<Tenant>.UpdateItemAsync(id, tenant); 
    } 

问题是它直接返回文档。应该是吧

    public async Task<IHttpActionResult> PostTenant(string id, Tenant tenant) 
    { 
        if (!ModelState.IsValid) 
        { 
            return BadRequest(ModelState); 
        } 
 
        var result = await DocumentDBRepository<Tenant>.UpdateItemAsync(id, tenant); 
 
        return Ok(result); 
    } 

返回正确的类型。