【问题标题】:Why is MVC attribute routing not matching this GUID?为什么 MVC 属性路由与此 GUID 不匹配?
【发布时间】:2020-12-15 17:42:20
【问题描述】:

我正在尝试使用属性路由。由于各种原因,我的密码重置所需的 Guid 参数之一不能在 queryString 中,因此我不得不将它放在路径中。这本身不是问题,除了我无法让 resetToken 填充到我的控制器中 - 即使它与基于我定义的 Route 属性的控制器方法匹配。

所以给定这个网址:

http://example.com/Account/ResetPasswordBySMS/96b7ba88-65e0-4dbc-a012-e69545a29a55/?userid=9d394579-afbb-49c4-ba21-877f4dad91fa

...不会在这里填充“resetToken”? (总是为空)

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-4 asp.net-mvc-routing


    【解决方案1】:

    将您的操作更改为:

    [Route("~/Account/ResetPasswordBySMS/{resetToken?}")]
    public ActionResult ResetPasswordBySMS(string resetToken, [FromQuery] string userId, [FromQuery] string code)
    {
     var guidResetToken= new Guid(resetToken);
    }
    

    我在 Postman 中测试了 url http://localhost:55480/Account/ResetPasswordBySMS/96b7ba88-65e0-4dbc-a012-e69545a29a55?userid=9d394579-afbb-49c4-ba21-877f4dad91fa&code=fghjk。它正在工作。

    将查询字符串与路由混合并不是一个好主意。我也会在路由中添加 userId 和代码:

    [Route("~/Account/ResetPasswordBySMS/{resetToken?}/{userId?}/{code?}
    public ActionResult ResetPasswordBySMS(string resetToken, string userId, string code)
    

    我可以在重置令牌之后和之前看到 url 错误 - 斜杠?标记。这个斜线应该没有了。

    【讨论】:

    • 请检查我更新的答案。你能写一个代码是如何调用这个网址的吗?
    • 不幸的是我不能使用这种方法。这必须是我如何在我的问题中提出的。我可以创建 URL,但我无法控制的第 3 方附加“?code=xxx&userId=yyy”,因此 URL 必须采用该格式。
    • 我试图将 ID 放在路径中,因为你不能有两个查询字符串,所以我不能有 /ResetPasswordBySMS/?resetToken=x?userId=y&code=z
    • 你必须尝试这样的url(不要在resetToken之后放/):example.com/Account/ResetPasswordBySMS/…....
    • 我用经过测试的解决方案更新了我的答案。它在我的测试环境中工作。
    猜你喜欢
    • 2019-11-25
    • 2017-10-15
    • 2018-11-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-26
    • 2023-03-21
    • 2012-07-13
    • 1970-01-01
    相关资源
    最近更新 更多