[英]How to setup Web API controller to route request to method parameter?
I have a Web API setup and I want to pass a string parameter to the GetAutomation method. 我有一个Web API设置,我想将字符串参数传递给GetAutomation方法。 In Global.asax I have: 在Global.asax中,我有:
protected void Application_Start(object sender, EventArgs e)
{
RouteTable.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{testName}",
defaults: new { id = System.Web.Http.RouteParameter.Optional });
RouteTable.Routes.MapHttpRoute(
name: "DefaultApiWithAction",
routeTemplate: "api/{controller}/{action}/{testName}");
}
In my AutomationController.cs, I have: 在我的AutomationController.cs中,我有:
[ActionName("GetAutomation")]
[HttpGet]
public string StartAutomation(string testName)
{
//string testName = "MyTest123";
Vmware.StartAutomation("automation-server", testName);
return "Automation started for " + testName;
}
If I remove the testName parameter from StartAutomation and call: 如果我从StartAutomation中删除testName参数并调用:
http://localhost/api/Automation/GetAutomation
it works. 有用。 If I put it back in and try 如果我放回去尝试
http://localhost/api/Automation/GetAutomation/Test123
it fails with a 404 error. 它失败并显示404错误。 Any idea what I''m doing wrong? 知道我在做什么错吗? Thanks, J. 谢谢,J。
Remove the {testName} from the "routeTemplate"
protected void Application_Start(object sender, EventArgs e)
{
RouteTable.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{testName}",
defaults: new { id = System.Web.Http.RouteParameter.Optional });
RouteTable.Routes.MapHttpRoute(
name: "DefaultApiWithAction",
routeTemplate: "api/{controller}/{action}");
}
And include the parameter as a queryString 并包含参数作为queryString
E : api/Automation/GetAutomation?testName=Test123 E:api / Automation / GetAutomation?testName = Test123
This is regarding the question of the comment , if I understood properly the only thing you have to do is declare the input of the parameters on the function as 这是关于注释的问题,如果我正确理解的话,唯一要做的就是将函数上的参数输入声明为
[ActionName("RunMyStuff")]
public string MyMethodName(bool isAtomic, string blabla, int delayOfSec)
{
....Code Placed Here
}
So the call will be like the other one , but now you have more than 1 parameters so you have to use the contact queryString parameters. 因此,调用将与另一个调用类似,但是现在您拥有多个参数,因此您必须使用contact queryString参数。
E : api/Automation/RunMyStuff?isAtomic=true&blabla=mystring&delayOfSec=23 E:api /自动化/ RunMyStuff?isAtomic = true&blabla = mystring&delayOfSec = 23
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.