无法将类型“System.Net.HttpResponseMessage”隐式转换为我的对象

问题描述 投票:0回答:1

我对此很陌生,我面临着这个我不理解的问题。我正在尝试创建一个代码,可以在其中更新数据库中用户的数据。下面的代码块显示错误:

using LMSC.Models;
using System.Net.Http;
using System.Net.Http.Json;

namespace LMSC.Blazor.Services
{
    public class UserService : IUserService
    {
        private readonly HttpClient httpClient;
        public UserService(HttpClient httpClient)
        {
            this.httpClient = httpClient;
        }

        public async Task<User> AddUser(User newUser)
        {
            return await httpClient.PostAsJsonAsync<User>("/api/users", newUser); //error here
        }

        public async Task<User> UpdateUser(User updatedUser)
        {
            return await httpClient.PutAsJsonAsync<User>("api/users", updatedUser); //error here
        }
    }
}

这是我的 UserService 文件,它具有执行此操作所需的功能。我从项目中的 API 中拖动数据。它可以很好地获取数据,但我无法更新现有用户也无法创建新用户。 这是我的 API 中的 UserRepository,用于将信息保存到数据库中或将其拖出数据库:

using LMSC.Models;
using Microsoft.EntityFrameworkCore;

namespace LMSC.API.Models
{
    public class UserRepository : IUserRepository
    {
        private readonly AppDbContext appDbContext;

        public UserRepository(AppDbContext appDbContext)
        {
            this.appDbContext = appDbContext;
        }

        public async Task<User> UpdateUser(User user)
        {
            var result = await appDbContext.Users.FirstOrDefaultAsync(u => u.UserID == user.UserID);

            if (result == null)
            {
                result.FirstName = user.FirstName;
                result.LastName = user.LastName;
                result.Email = user.Email;
                result.RoleID = user.RoleID;
                result.DateOfBirth = user.DateOfBirth;
                result.Gender = user.Gender;
                result.PhotoPath = user.PhotoPath;

                await appDbContext.SaveChangesAsync();

                return result;
            }

            return null;
        }

        public async Task<User> AddUser(User user)
        {
            var result = await appDbContext.Users.AddAsync(user);
            await appDbContext.SaveChangesAsync();
            return result.Entity;
        }
    }
}

这是使用 try-catch 方法检查可能错误的 UserController 文件:

using LMSC.API.Models;
using LMSC.Models;
using Microsoft.AspNetCore.Mvc;

namespace LMSC.API.Controllers
{
    [Route("/api/[controller]")]
    [ApiController]
    public class UsersController : ControllerBase
    {
        private readonly IUserRepository userRepository;
        public UsersController(IUserRepository userRepository)
        {
            this.userRepository = userRepository;
        }


        [HttpPost]
        public async Task<ActionResult<User>> AddUser(User user)
        {
            try
            {
                if (user == null)
                {
                    return BadRequest();
                }

                var createdUser = await userRepository.AddUser(user);

                return CreatedAtAction(nameof(GetUser), new { id = createdUser.UserID }, createdUser);
            }
            catch (Exception)
            {
                return StatusCode(StatusCodes.Status500InternalServerError, "Error retrieving data from the Database");
            }
        }

        [HttpPut]
        public async Task<ActionResult<User>> UpdateUser(User user)
        {
            try
            {
                var userToUpdate = await userRepository.GetUser(user.UserID);

                if (userToUpdate == null)
                {
                    return NotFound($"User with ID = {user.UserID} not found");
                }

                return await userRepository.UpdateUser(user);
            }
            catch (Exception)
            {
                return StatusCode(StatusCodes.Status500InternalServerError, "Error retrieving data from the Database");
            }
        }
    }
}

在 UserService 文件上,它不断显示错误消息“CS0029 - 无法将类型‘System.Net.HttpResponseMessage’隐式转换为‘LMSC.Models.User’”。我尝试在网上寻找可能的解释,并回顾我的教程,以防我错过了一些东西,但我还没有找到任何东西。

我对此很陌生,所以这很可能是显而易见的事情,但如果您愿意让我了解我所缺少的内容,那将意义重大。

c# asp.net-core blazor dotnet-httpclient api-design
1个回答
0
投票

您的控制器返回的是

HttpResponseMessage
,而不是
User

您需要读取返回的

HttpResponseMessage
状态并解码内容。

public async Task<User> AddUser(User newUser)
{
     var response = await httpClient.PostAsJsonAsync<User>("/api/users", newUser);
    if (response.IsSuccessStatusCode)
    {
       var result = await response.Content.ReadFromJsonAsync<User>();
       //.....
       return result;
    }
       //..... Handle bad response

}
© www.soinside.com 2019 - 2024. All rights reserved.