Wep Api - 405方法不允许

时间:2017-04-14 22:33:11

标签: rest asp.net-web-api2 attributerouting

我有一个带有控制器的Web Api项目,该控制器具有GET,DELETE,POST和PUT方法。

当我尝试对此控制器执行POST或PUT时,我总是得到405 Method Not Allowed错误。发送的数据看起来有效,它只是一个具有六个简单属性的对象。我在我的方法中放了一个断点,正如在这种情况下预期的那样,它不会被击中。我注册了一个DelegatingHandler(在Web Api - Catch 405 Method Not Allowed中提到)来检查传入的请求和传出的响应,我可以告诉我的请求是由Api处理的(意味着问题不在于客户端)。我还使用Fiddler检查请求/响应,响应标题在Security,Allow:DELETE,GET下说。

这清楚地告诉我,出于某种原因,不允许PUT和POST,即使我有[HttpPost]和[HttpPut]属性修饰的方法,并且我已经知道正确配置了路由。我正在使用默认路由,但也有使用属性路由的方法。

这听起来可能存在某种安全问题,但是,我能够在我的其他控制器中进行POST和PUT,并且我认为没有任何差异,我认为这会导致问题。< / p>

以下是我的代码片段:

public class PricesController : ApiController
{
    // DELETE: api/Prices/5
    [HttpDelete]
    [ResponseType(typeof(Price))]
    [Route("api/Prices/{id:int}")]
    public async Task<IHttpActionResult> DeletePrice(int id)
    {
      // code omitted
    }

    // GET: api/Prices/5
    [HttpGet]
    [ResponseType(typeof(Price))]
    [Route("api/Prices/{id:int}")]
    public async Task<IHttpActionResult> GetPrice(int id)
    {
      // code omitted
    }

    // GET: api/Prices
    [HttpGet]
    [Route("api/Prices")]
    public IQueryable<Price> GetPrices()
    {
      // code omitted
    }

    // POST: api/Prices
    [HttpPost]
    [ResponseType(typeof(Price))]
    [Route("api/Prices", Name = "Prices")]
    public async Task<IHttpActionResult> PostPrice(Price price)
    {
      // code omitted
    }

    // PUT: api/Prices/5
    [HttpPut]
    [ResponseType(typeof(void))]
    [Route("api/Prices/{id:int}")]
    public async Task<IHttpActionResult> PutPrice(int id, Price price)
    {
      // code omitted
    }
}

任何帮助将不胜感激。我花了一整天时间试图解决这个问题。

1 个答案:

答案 0 :(得分:0)

听起来它没有正确绑定。

您可以尝试在行动中使用[FromBody]装饰价格吗?

PostPrice([FromBody] Price price)