c# - 模型未绑定(bind)到 RedirectToRoute

标签 c# asp.net-web-api model-binding

我已经上下搜索了我认为是常见问题的答案,但未能找到解决方案...所以问题是:

我有以下模型:

public class UserModel
    {
        public string userType { get; set; }
        public string userName { get; set; }
        public string passWord { get; set; }
        public string userClaim { get; set; }
        public string redirectAction { get; set; }
        public string jsonWebToken { get; set; }
        public string message { get; set; }

    }

我在 Web API Controller 中“填充”这个模型:

return RedirectToRoute("Default", new
            {
                controller = "Redirect",
                action = "SsoRedirect",
                method = "Get",
                userType = thisUser.userType,
                userName = thisUser.userName,
                passWord = thisUser.passWord,
                userClaim = thisUser.userClaim,
                redirectAction = thisUser.redirectAction,
                jsonWebToken = thisUser.jsonWebToken,
                message = thisUser.message,

            });

然后像这样将它传递给另一个 Controller :

[HttpGet]
[Route("SsoRedirect")]     
public IHttpActionResult SsoRedirect(UserModel myUser)
{
    ....
}

问题:myUser 以空值出现。模型上的所有属性都没有被绑定(bind)。

这是我确定的:

  1. 我的路由很好,因为实际上命中了 SsoRedirect 中的一个断点。
  2. 当我在 fiddler 中进行跟踪时,我可以看到正在传递的所有适当的查询字符串参数。
    1. 我知道我无法传递具有枚举和其他复杂数据类型的复杂对象,因此一切都仅限于字符串。

所以...对于我的生活,我无法弄清楚为什么模型没有约束力并希望在这里得到一些帮助。

最佳答案

如果您将复杂类型作为参数传入 Web API Controller 并通过 GET 访问它,您需要告诉 Controller 它可以根据请求中发送的查询字符串参数创建对象。添加 [FromUri] 属性,您的对象应该可以正常创建:

[HttpGet]
[Route("SsoRedirect")]     
public IHttpActionResult SsoRedirect([FromUri]UserModel myUser)
{
    ....
}

关于c# - 模型未绑定(bind)到 RedirectToRoute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31566980/

相关文章:

c# - ASP.NET : Cannot add or update child row: a foreign key constraint fails

C# Wcf 连接导致 TCP/IP 端口耗尽

asp.net-web-api - Asp.net web api 中的 DbGeometry 序列化问题

jquery - 使用 asp.net core 和 Jquery 从 ajax 请求将对象绑定(bind)到 asp mvc Controller

c# - 在 .Net Core 中禁用模型绑定(bind)器

asp.net-mvc - ASP.NET MVC - ICollection<T> 映射到 Enum 的 EditorTemplate 问题

C# 分块数组

c# - 如何从 C# Controller 重定向到外部 URL

c# - Web API Controller 的构造函数是如何调用的?

asp.net-mvc - 当我有一个可为空的参数时,ModelState.IsValid 为 false