【问题标题】:ASP.Net Web API Routing with optional parameters带有可选参数的 ASP.Net Web API 路由
【发布时间】:2017-08-30 09:35:50
【问题描述】:

我有一个如下所示的 Web API 端点 -

[HttpPost]  
[ActionName("ResetPassword")]   
public HttpResponseMessage ResetPassword(string userName, string Template, string SubjectKey,[FromBody] Dictionary<string, string> KeyWords)

如您所见,WebAPI 有 4 个参数。但是,除了第一个参数“userName”之外,所有其他参数都是可选的。所有参数都是字符串类型,默认为空。

我已经配置了路由,使用基于约定的路由(这是一个遗留项目)。

Config.Routes.MapHttpRoute(
             name: "ResetPasswordResetV2",
             routeTemplate: "Email/ResetPassword",
             defaults: new { controller = "Email", action = "ResetPassword", routeValue = true });

我希望它可以与任何一个一起使用 -

http://{base address}/V2/Core/Email/ResetPassword?userName=hdhd@hshshs.com&template=&subjectKey=
http://{base address}/V2/Core/Email/ResetPassword?userName=hdhd@hshshs.com

不工作。我得到一个 404。任何提示我做错了什么。我已经阅读了所有类型的 SO 和 doc 链接,看起来有太多信息需要处理。

另外,'routeValue = true' 是什么意思?

更新:我让它与第一个 URL 一起使用,但我希望它也可以与第二个 API 一起使用。还有一个信息,我的控制器还有一个具有相似输入参数集的动作,但动作名称不同(这会以任何方式搞砸吗?)

【问题讨论】:

  • 你需要澄清什么是不工作的意思。你得到一个错误。是动作命中,但参数为空。期望的行为是什么?
  • 我更新了我的问题。基本上我得到了 404。
  • 那么你需要提供一个minimal reproducible example 可以用来重现问题。显示更多目标控制器。以及如何配置路由的更多信息。这些通常是可能导致您的问题的两个主要方面。

标签: asp.net asp.net-web-api asp.net-mvc-routing asp.net-web-api-routing asp.net-routing


【解决方案1】:

试试这个:

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{userName}/{template}/{subjectKey}",
    defaults: new { controller = "Email", action = "ResetPassword", template = UrlParameter.Optional, subjectKey = UrlParameter.Optional 
});

其中,userName 是必需的,但 templatesubjectKey 是可选的。

URL 将如下所示(假设 template 等于 template1 并且 subjectKey 等于 3):

http://{base address}/V2/Core/Email/ResetPassword/hdhd@hshshs.com/template1/3

或者,没有任何参数,只有userName

http://{base address}/V2/Core/Email/ResetPassword/hdhd@hshshs.com

如果完全有必要,您可以将信息作为查询参数发送,但您必须在 Controller 中指明。

输入的网址:

Controller 收到的参数:

【讨论】:

  • 在我的例子中,客户端将参数作为查询参数的一部分发送。在您展示的示例中,参数作为路由值的一部分发送。有没有办法对查询参数做同样的事情?
  • 我刚刚做了一个测试,是的,可以作为查询参数发送,我会更新我的答案
猜你喜欢
  • 2014-04-18
  • 2015-10-09
  • 1970-01-01
  • 2017-07-14
  • 1970-01-01
  • 2011-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多