带有可选参数的ASP.Net Web API路由

时间:2017-04-05 00:23:38

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

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

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

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

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

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和文档链接,看起来有太多的信息需要处理。

此外,'routeValue = true'意味着什么?

更新:我使用了第一个URL,但我希望它也可以使用第二个API。还有一个Info,我的控制器还有一个具有类似输入参数集的Action,但是动作名称是不同的(这可能会以任何方式弄乱它吗?)

1 个答案:

答案 0 :(得分: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是可选的。

网址将如下所示(表示template等于template1subjectKey等于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中进行指示。

输入的网址:

enter image description here

Controller收到的参数:

enter image description here

相关问题