微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

错误:传递到 ViewDataDictionary 的模型项的类型为“System.Net.Http.HttpResponseMessage”,但是这

如何解决错误:传递到 ViewDataDictionary 的模型项的类型为“System.Net.Http.HttpResponseMessage”,但是这

在我的 Asp.net 核心项目中,出现 ERROR :The model item passed into the ViewDataDictionary is of type 'System.Net.Http.HttpResponseMessage',but this ViewDataDictionary instance requires a model item of type MENTOR.Models.Mentor 错误。我想要做的是;

login controller 中,我将登录名和密码数据作为参数发送给 API,所有我都需要从 API 响应中获取 MentorId(Mentor 的哪个属性属性。然后所有我需要将此 ID 发送到 Profilementor controller 操作。然后我将从来自 login controller 的会话中获取此 ID,然后将其发送到 API 并使用响应模型填充配置文件模型。我的问题与其他相同问题的不同之处在于我不会从 mentor controllerlogin controller 发送和建模。我只需要触发 profile
mentor controller 动作 这是我的 login controller;

[HttpPost]
    public async Task<IActionResult> Login(User user)
    {
        using (var client = new HttpClient())
        {
            IList<keyvaluePair<string,string>> userCollection = new List<keyvaluePair<string,string>> {
{ new keyvaluePair<string,string>("email",user.email) },{ new keyvaluePair<string,string>("password",user.password) }
            };          
            var result = await client.PostAsync("http://localhost:3000/mentor/login",new FormUrlEncodedContent(userCollection));
            string resultContent = await result.Content.ReadAsstringAsync();
            var response = JsonConvert.DeserializeObject<Mentor>(resultContent);
            HttpContext.Session.SetInt32("mentorId",response.mentorId);
            if (result.StatusCode == System.Net.HttpStatusCode.OK)
            {
                return RedirectToAction("Profile","Mentor");
            }

这是我的mentor controller

[HttpGet]
    public async Task<IActionResult> Profile()
    {
        using (var client = new HttpClient())
        {
            var id = HttpContext.Session.GetInt32("mentorId");
            var response = await client.GetAsync("http://localhost:3000/mentor/getProfileInfo/" + id);
            string responseContent = await response.Content.ReadAsstringAsync();
            var result = JsonConvert.DeserializeObject<Mentor>(responseContent);
            result.mentorId = Convert.ToInt32(id);
            if (response.StatusCode == System.Net.HttpStatusCode.OK)
            {
                return View(response);
            }
            else
            {
                return StatusCode(404,result.mentorId);
            }
        }
    }

和我的profile view模型;

@model MENTOR.Models.Mentor

提前谢谢:))

解决方法

修复错误 - 而不是使用响应使用结果:

if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
var result = JsonConvert.DeserializeObject<Mentor>(responseContent);
            result.mentorId = Convert.ToInt32(id); //Maybe you don't need it???
           
                return View(result);
            }
            else
            {
                return StatusCode(404,id);
            }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。