为什么仅某些操作需要 HttpGet?
Why is HttpGet required only for some actions?
我先大概说一下情况:
我有一个基本控制器,如下所示:
public class SearchRequestController : ApiController
{
public IEnumerable<ObjectA> GetAllRequests() {...}
{}
public IEnumerable<ObjectA> GetLatestRequest() {...}
{}
}
使用以下路由
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
我可以轻松使用以下功能
Http://myServer/myvirtualdirectory/api/SearchRequest/GetAllRequests
Http://myServer/myvirtualdirectory/api/SearchRequest/GetLatestRequest
现在我想添加以下控制器
public class UserController : ApiController
{
public IEnumerable<UserObject> SearchUsersByInput() {...}
}
但是下面的GET不行
Http://myServer/myvirtualdirectory/api/User/SearchUsersByInput
I'm getting a 405: {"Message":"The requested resource does not support http method 'GET'."}
然而,当我按如下方式更改我的功能时,它会起作用:
public class UserController : ApiController
{
[HttpGet]
public IEnumerable<UserObject> SearchUsersByInput() {...}
}
问题:
有人可以解释这种行为的起源吗?我做错了什么或者我的路由有问题吗?
请参考posthere
您将看到您可以使用命名约定(这就是名称中带有 Get 的方法起作用的原因),或者您可以通过使用正确的 HTTP 属性修饰操作来显式指定操作的 HTTP 方法。
这是 asp.net 中网络服务的默认行为 - 它们不支持 GET
方法,除非明确指定它们应该支持。
所以只需使用 [HttpGetAttribute]
方法即可通过 http:
支持 GET
Represents an attribute that is used to restrict an action method so that the method handles only HTTP GET requests.
我先大概说一下情况:
我有一个基本控制器,如下所示:
public class SearchRequestController : ApiController
{
public IEnumerable<ObjectA> GetAllRequests() {...}
{}
public IEnumerable<ObjectA> GetLatestRequest() {...}
{}
}
使用以下路由
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
我可以轻松使用以下功能
Http://myServer/myvirtualdirectory/api/SearchRequest/GetAllRequests
Http://myServer/myvirtualdirectory/api/SearchRequest/GetLatestRequest
现在我想添加以下控制器
public class UserController : ApiController
{
public IEnumerable<UserObject> SearchUsersByInput() {...}
}
但是下面的GET不行
Http://myServer/myvirtualdirectory/api/User/SearchUsersByInput
I'm getting a 405: {"Message":"The requested resource does not support http method 'GET'."}
然而,当我按如下方式更改我的功能时,它会起作用:
public class UserController : ApiController
{
[HttpGet]
public IEnumerable<UserObject> SearchUsersByInput() {...}
}
问题: 有人可以解释这种行为的起源吗?我做错了什么或者我的路由有问题吗?
请参考posthere
您将看到您可以使用命名约定(这就是名称中带有 Get 的方法起作用的原因),或者您可以通过使用正确的 HTTP 属性修饰操作来显式指定操作的 HTTP 方法。
这是 asp.net 中网络服务的默认行为 - 它们不支持 GET
方法,除非明确指定它们应该支持。
所以只需使用 [HttpGetAttribute]
方法即可通过 http:
GET
Represents an attribute that is used to restrict an action method so that the method handles only HTTP GET requests.