Bill Software Engineer
Bill Software Engineer

Reputation: 7822

How do I set default Action for Controller?

So I have 2 controller:

[AllowCrossSiteJson]
public class ItemController : ApiController {
    [HttpGet]
    public LinkedList<Object> FindItem([FromUri]ItemQuery query) {
        ....
    }
}

And

[AllowCrossSiteJson]
public class SubDepController : ApiController
{

    [HttpGet]
    public LinkedList<Object> FindSubDep(string ID) {
        ....
    }
}

Here is the thing, I try to call both:

http://localhost:43751/api/SubDep

http://localhost:43751/api/Item

And the Item Controller works but the SubDep does not work! Why is that?

Here is my WebApiConfig:

    public static void Register(HttpConfiguration config) {
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
        config.Routes.MapHttpRoute(
            name: "withAction",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }

The error I get back is this:

{"Message":"No HTTP resource was found that matches the request URI 'http://localhost:43751/api/SubDep'.","MessageDetail":"No action was found on the controller 'SubDep' that matches the request."}

BONUS question:

How does ASP.NET MVC know that I try to hit:

http://localhost:43751/api/Item

It automatically go to the FindItem Action? It's like pure MAGIC to me!!

Upvotes: 1

Views: 249

Answers (2)

Lin
Lin

Reputation: 15188

When you try to call FindSubDep action, your query string should be like belwo:

http://localhost:43751/api/SubDep/1

Upvotes: 1

Neel
Neel

Reputation: 220

For the bonus question. It gets to the correct action because of the HTTP verb [GET] in your case, when you make a GET request for

http://localhost:43751/api/Item

it will find an action with [HttpGet] attribute on Item controller.

Upvotes: 1

Related Questions