【问题标题】:ASP.NET core return Bad object from controllerASP.NET 核心从控制器返回坏对象
【发布时间】:2018-09-20 08:47:27
【问题描述】:

我有 repo 方法,即更新数据库中的条目。这是来自 repo 方法的代码

 public async Task<string> UpdateProfile(string email, string firstname, string lastname, DateTime birthday)
    {
        string result;
        var user = _context.AspNetUsers.Where(x => x.Email == email).FirstOrDefault();
        user.FirstName = firstname;
        user.LastName = lastname;
        user.Birthday = birthday;
        await _context.SaveChangesAsync();
        result = "Updated";
        return result;
    }

这是我从控制器调用它的方式

[HttpPost]
    public JsonResult UpdateProfile([FromBody] ProfileViewModel profile)
    {
        var result = _profile.UpdateProfile(profile.Email, profile.FirstName, profile.LastName, profile.Birthday);
        return Json(result);
    }

但在邮递员中我看到Bad object,但条目已更新。

为什么我会得到这个以及如何解决这个问题?

感谢您的帮助。

【问题讨论】:

  • 你的意思是坏对象还是Bad Request
  • 你不应该在等待任务吗?否则,您的控制器方法将在异步回调分配结果之前命中 return 语句。试试var result = await _profile.UpdateProfile(profile.Email, profile.FirstName, profile.LastName, profile.Birthday);

标签: json asp.net-core asp.net-core-mvc


【解决方案1】:

更新方法如下:

[HttpPost]
    public async Task<IActionResult> UpdateProfile([FromBody] ProfileViewModel profile)
    {
        var result = await _profile.UpdateProfile(profile.Email, profile.FirstName, profile.LastName, profile.Birthday);
        return Ok(result);
    }

将返回类型更改为 IActionResult,并使控制器操作异步。

【讨论】:

  • 是的,但你有错误。 public async Task&lt;IActionResult&gt;是正确的
猜你喜欢
  • 2017-07-29
  • 2020-05-07
  • 1970-01-01
  • 1970-01-01
  • 2017-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多