简体   繁体   中英

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. In Global.asax I have:

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:

[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:

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. Any idea what I''m doing wrong? Thanks, 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

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.

E : api/Automation/RunMyStuff?isAtomic=true&blabla=mystring&delayOfSec=23

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM