请求的资源不支持HTTP方法GET

Eli*_*eth 5 c# asp.net-web-api asp.net-web-api2

当我运行这个url时:/api/users/1它只在我使用HttpDelete-Attribute时映射到Delete操作.这种行为的原因是什么?

否则我收到他的消息:请求的资源不支持HTTP方法GET

[RoutePrefix("api/users")]
public class UserController : ApiController
{
    private readonly IUserService _userService;
    public UserController(IUserService userService)
    {
        _userService = userService;
    }

    [Route("")]
    public HttpResponseMessage Get()
    {
        return Request.CreateResponse<IEnumerable<UserDTO>>(HttpStatusCode.OK, _userService.GetUsers());
    } 

    [Route("{id:int}")]
    [HttpDelete]
    public HttpResponseMessage Delete(int id)
    {
        _userService.Delete(id);
        return Request.CreateResponse(HttpStatusCode.OK, "User was deleted successfully");
    }
}
Run Code Online (Sandbox Code Playgroud)

这些是我的路线:

 config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
               name: "ActionApi",
               routeTemplate: "api/{controller}/{id}",
               defaults: new { id = RouteParameter.Optional }
           );

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { controller = "Home", action = "Start", id = RouteParameter.Optional }
            );
Run Code Online (Sandbox Code Playgroud)

Mis*_*pic 16

按照惯例,HTTP谓词将匹配以该HTTP谓词为前缀的操作名称.

所以,它抱怨你没有HTTP GET的动作,这是你用浏览器发出简单请求时使用的动词.您需要一个名为的行为:

public HttpResponseMessage Get(int id)
Run Code Online (Sandbox Code Playgroud)

甚至

public HttpResponseMessage GetUser(int id)
Run Code Online (Sandbox Code Playgroud)

显然,如果您使用DELETE发出请求,它将映射到您已定义的删除操作.

参考:http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api

"要查找操作,Web API会查看HTTP方法,然后查找名称以该HTTP方法名称开头的操作.例如,对于GET请求,Web API会查找以"Get .."开头的操作. ",例如"GetContact"或"GetAllContacts".此约定仅适用于GET,POST,PUT和DELETE方法.您可以通过控制器上的属性启用其他HTTP方法.我们稍后会看到一个示例".