如何为Controller设置默认操作?

时间:2013-12-13 19:48:26

标签: asp.net-mvc routing

所以我有2个控制器:

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

[AllowCrossSiteJson]
public class SubDepController : ApiController
{

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

这是事情,我试着同时打电话:

http://localhost:43751/api/SubDep

http://localhost:43751/api/Item

项目控制器工作但SubDep不起作用!那是为什么?

这是我的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 }
        );
    }

我得到的错误是:

{"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."}

奖金问题:

ASP.NET MVC如何知道我试图点击:

http://localhost:43751/api/Item

它会自动转到FindItem Action吗?对我来说就像纯魔术一样!!

2 个答案:

答案 0 :(得分:1)

当您尝试调用FindSubDep操作时,您的查询字符串应如下所示:

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

答案 1 :(得分:1)

奖金问题。由于您的情况下的HTTP动词[GET],当您发出GET请求

时,它会得到正确的操作
http://localhost:43751/api/Item

它会在Item控件上找到[HttpGet]属性的动作。