ASP。NET Web Api:请求的资源不支持http方法“GET”

时间:2022-09-11 13:30:02

I've got the following action on an ApiController:

我有一个ApiController的动作:

public string Something()
{
    return "value";
}

And I've configured my routes as follows:

我将我的路线配置如下:

routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{action}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

In the beta, this worked just fine, but I just updated to the latest Release Candidate and now I'm seeing errors on calls like this:

在beta版中,这个功能很好,但是我刚刚更新了最新的候选版本,现在我看到像这样的调用出现了错误:

The requested resource does not support http method 'GET'.

请求的资源不支持http方法“GET”。

Why doesn't this work anymore?

为什么这个不再有效?

(I suppose I could get rid of {action} and just make a ton of controllers, but that feels messy.)

(我想我可以去掉{action},只做大量的控制器,但感觉很乱。)

8 个解决方案

#1


97  

If you have not configured any HttpMethod on your action in controller, it is assumed to be only HttpPost in RC. In Beta, it is assumed to support all methods - GET, PUT, POST and Delete. This is a small change from beta to RC. You could easily decore more than one httpmethod on your action with [AcceptVerbs("GET", "POST")].

如果您没有在控制器上的操作上配置任何HttpMethod,那么假设它只是RC中的HttpPost。在Beta版本中,它被假定支持所有方法——GET、PUT、POST和Delete。这是从beta到RC的一个小变化。使用[accept动词(GET, POST)],你可以很容易地将多个httpmethod删除。

#2


51  

All above information is correct, I'd also like to point out that the [AcceptVerbs()] annotation exists in both the System.Web.Mvc and System.Web.Http namespaces.

以上信息都是正确的,我还想指出[accept谓词()]注释在System.Web中都存在。Mvc和包含。Http命名空间。

You want to use the System.Web.Http if it's a Web API controller.

您需要使用System.Web。Http,如果它是一个Web API控制器。

#3


26  

Although this isn't an answer to the OP, I had the exact same error from a completely different root cause; so in case this helps anybody else...

虽然这不是OP的答案,但我从完全不同的根本原因得到了完全相同的错误;如果这对其他人有帮助…

The problem for me was an incorrectly named method parameter which caused WebAPI to route the request unexpectedly. I have the following methods in my ProgrammesController:

我遇到的问题是一个命名不正确的方法参数,它导致WebAPI意外地路由请求。在我的程序控制器中有以下方法:

[HttpGet]
public Programme GetProgrammeById(int id)
{
    ...
}

[HttpDelete]
public bool DeleteProgramme(int programmeId)
{
    ...
}

DELETE requests to .../api/programmes/3 were not getting routed to DeleteProgramme as I expected, but to GetProgrammeById, because DeleteProgramme didn't have a parameter name of id. GetProgrammeById was then of course rejecting the DELETE as it is marked as only accepting GETs.

删除请求……/api/程序/3没有像我所期望的那样被路由到deleteprogram,而是GetProgrammeById,因为deleteprogram没有id的参数名,所以,GetProgrammeById当然是拒绝删除,因为它被标记为只接受get。

So the fix was simple:

所以解决办法很简单:

[HttpDelete]
public bool DeleteProgramme(int id)
{
    ...
}

And all is well. Silly mistake really but hard to debug.

和一切都好。这个愚蠢的错误真的很难调试。

#4


17  

If you are decorating your method with HttpGet, add the following using at the top of the controller:

如果您正在使用HttpGet装饰方法,请在控制器顶部添加以下内容:

using System.Web.Http;

If you are using System.Web.Mvc, then this problem can occur.

如果你正在使用System.Web。Mvc,这个问题就会出现。

#5


14  

This is certainly a change from Beta to RC. In the example provided in the question, you now need to decorate your action with [HttpGet] or [AcceptVerbs("GET")].

这当然是由Beta到RC的变化。在问题中提供的示例中,您现在需要用[HttpGet]或[accept动词(GET)]来修饰您的操作。

This causes a problem if you want to mix verb based actions (i.e. "GetSomething", "PostSomething") with non verb based actions. If you try to use the attributes above, it will cause a conflict with any verb based action in your controller. One way to get arount that would be to define separate routes for each verb, and set the default action to the name of the verb. This approach can be used for defining child resources in your API. For example, the following code supports: "/resource/id/children" where id and children are optional.

如果你想混合使用动词的动作(例如。“GetSomething”,“PostSomething”)使用非动词的动作。如果您试图使用上面的属性,它将导致与控制器中任何基于谓词的操作发生冲突。获取arount的一种方法是为每个动词定义单独的路由,并将默认动作设置为该动词的名称。这种方法可用于在API中定义子资源。例如,以下代码支持:“/resource/id/children”,其中id和子项是可选的。

        context.Routes.MapHttpRoute(
           name: "Api_Get",
           routeTemplate: "{controller}/{id}/{action}",
           defaults: new { id = RouteParameter.Optional, action = "Get" },
           constraints: new { httpMethod = new HttpMethodConstraint("GET") }
        );

        context.Routes.MapHttpRoute(
           name: "Api_Post",
           routeTemplate: "{controller}/{id}/{action}",
           defaults: new { id = RouteParameter.Optional, action = "Post" },
           constraints: new { httpMethod = new HttpMethodConstraint("POST") }
        );

Hopefully future versions of Web API will have better support for this scenario. There is currently an issue logged on the aspnetwebstack codeplex project, http://aspnetwebstack.codeplex.com/workitem/184. If this is something you would like to see, please vote on the issue.

希望未来版本的Web API能够更好地支持这个场景。目前,aspnetwebstack codeplex项目(http://aspnetwebstack.codeplex.com/workitem/184)上记录了一个问题。如果这是你想看到的,请投票决定。

#6


3  

Same problem as above, but vastly different root. For me, it was that I was hitting an endpoint with an https rewrite rule. Hitting it on http caused the error, worked as expected with https.

同样的问题,但却截然不同。对我来说,我是用一个https重写规则来达到一个端点。在http上点击它会导致错误,在https上正常工作。

#7


2  

Have the same Setup as OP. One controller with many actions... less "messy" :-)

拥有与操作系统相同的设置。一个有多个动作的控制器…少“凌乱”:-)

In my case i forgot the "[HttpGet]" when adding a new action.

在我的例子中,我在添加新操作时忘记了“[HttpGet]”。

[HttpGet]
public IEnumerable<string> TestApiCall()
{
    return new string[] { "aa", "bb" };
}

#8


0  

Replace the following code in this path

在此路径中替换以下代码

Path :

路径:

App_Start => WebApiConfig.cs

App_Start = > WebApiConfig.cs

Code:

代码:

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

#1


97  

If you have not configured any HttpMethod on your action in controller, it is assumed to be only HttpPost in RC. In Beta, it is assumed to support all methods - GET, PUT, POST and Delete. This is a small change from beta to RC. You could easily decore more than one httpmethod on your action with [AcceptVerbs("GET", "POST")].

如果您没有在控制器上的操作上配置任何HttpMethod,那么假设它只是RC中的HttpPost。在Beta版本中,它被假定支持所有方法——GET、PUT、POST和Delete。这是从beta到RC的一个小变化。使用[accept动词(GET, POST)],你可以很容易地将多个httpmethod删除。

#2


51  

All above information is correct, I'd also like to point out that the [AcceptVerbs()] annotation exists in both the System.Web.Mvc and System.Web.Http namespaces.

以上信息都是正确的,我还想指出[accept谓词()]注释在System.Web中都存在。Mvc和包含。Http命名空间。

You want to use the System.Web.Http if it's a Web API controller.

您需要使用System.Web。Http,如果它是一个Web API控制器。

#3


26  

Although this isn't an answer to the OP, I had the exact same error from a completely different root cause; so in case this helps anybody else...

虽然这不是OP的答案,但我从完全不同的根本原因得到了完全相同的错误;如果这对其他人有帮助…

The problem for me was an incorrectly named method parameter which caused WebAPI to route the request unexpectedly. I have the following methods in my ProgrammesController:

我遇到的问题是一个命名不正确的方法参数,它导致WebAPI意外地路由请求。在我的程序控制器中有以下方法:

[HttpGet]
public Programme GetProgrammeById(int id)
{
    ...
}

[HttpDelete]
public bool DeleteProgramme(int programmeId)
{
    ...
}

DELETE requests to .../api/programmes/3 were not getting routed to DeleteProgramme as I expected, but to GetProgrammeById, because DeleteProgramme didn't have a parameter name of id. GetProgrammeById was then of course rejecting the DELETE as it is marked as only accepting GETs.

删除请求……/api/程序/3没有像我所期望的那样被路由到deleteprogram,而是GetProgrammeById,因为deleteprogram没有id的参数名,所以,GetProgrammeById当然是拒绝删除,因为它被标记为只接受get。

So the fix was simple:

所以解决办法很简单:

[HttpDelete]
public bool DeleteProgramme(int id)
{
    ...
}

And all is well. Silly mistake really but hard to debug.

和一切都好。这个愚蠢的错误真的很难调试。

#4


17  

If you are decorating your method with HttpGet, add the following using at the top of the controller:

如果您正在使用HttpGet装饰方法,请在控制器顶部添加以下内容:

using System.Web.Http;

If you are using System.Web.Mvc, then this problem can occur.

如果你正在使用System.Web。Mvc,这个问题就会出现。

#5


14  

This is certainly a change from Beta to RC. In the example provided in the question, you now need to decorate your action with [HttpGet] or [AcceptVerbs("GET")].

这当然是由Beta到RC的变化。在问题中提供的示例中,您现在需要用[HttpGet]或[accept动词(GET)]来修饰您的操作。

This causes a problem if you want to mix verb based actions (i.e. "GetSomething", "PostSomething") with non verb based actions. If you try to use the attributes above, it will cause a conflict with any verb based action in your controller. One way to get arount that would be to define separate routes for each verb, and set the default action to the name of the verb. This approach can be used for defining child resources in your API. For example, the following code supports: "/resource/id/children" where id and children are optional.

如果你想混合使用动词的动作(例如。“GetSomething”,“PostSomething”)使用非动词的动作。如果您试图使用上面的属性,它将导致与控制器中任何基于谓词的操作发生冲突。获取arount的一种方法是为每个动词定义单独的路由,并将默认动作设置为该动词的名称。这种方法可用于在API中定义子资源。例如,以下代码支持:“/resource/id/children”,其中id和子项是可选的。

        context.Routes.MapHttpRoute(
           name: "Api_Get",
           routeTemplate: "{controller}/{id}/{action}",
           defaults: new { id = RouteParameter.Optional, action = "Get" },
           constraints: new { httpMethod = new HttpMethodConstraint("GET") }
        );

        context.Routes.MapHttpRoute(
           name: "Api_Post",
           routeTemplate: "{controller}/{id}/{action}",
           defaults: new { id = RouteParameter.Optional, action = "Post" },
           constraints: new { httpMethod = new HttpMethodConstraint("POST") }
        );

Hopefully future versions of Web API will have better support for this scenario. There is currently an issue logged on the aspnetwebstack codeplex project, http://aspnetwebstack.codeplex.com/workitem/184. If this is something you would like to see, please vote on the issue.

希望未来版本的Web API能够更好地支持这个场景。目前,aspnetwebstack codeplex项目(http://aspnetwebstack.codeplex.com/workitem/184)上记录了一个问题。如果这是你想看到的,请投票决定。

#6


3  

Same problem as above, but vastly different root. For me, it was that I was hitting an endpoint with an https rewrite rule. Hitting it on http caused the error, worked as expected with https.

同样的问题,但却截然不同。对我来说,我是用一个https重写规则来达到一个端点。在http上点击它会导致错误,在https上正常工作。

#7


2  

Have the same Setup as OP. One controller with many actions... less "messy" :-)

拥有与操作系统相同的设置。一个有多个动作的控制器…少“凌乱”:-)

In my case i forgot the "[HttpGet]" when adding a new action.

在我的例子中,我在添加新操作时忘记了“[HttpGet]”。

[HttpGet]
public IEnumerable<string> TestApiCall()
{
    return new string[] { "aa", "bb" };
}

#8


0  

Replace the following code in this path

在此路径中替换以下代码

Path :

路径:

App_Start => WebApiConfig.cs

App_Start = > WebApiConfig.cs

Code:

代码:

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