无法使用 PUT 或 POST 调用方法

Can't call method with PUT or POST

我可以使用 GET 通过 http://requestmaker.com/ 请求 API 方法,但是当我使用 POST 或 PUT 时 returns...

HTTP/1.1 403 Forbidden

这是方法...

[HttpPost]
[Route("api/sales")]
public object Put([FromBody] Sale sale)
{
   sale.DateTime = DateTime.Now;

   paymentRepository.Insert(sale);
   paymentRepository.Save();

   return Ok(new { id = sale.SaleId });
}

有什么想法吗?

请求headers是...

POST /admin/api/sales HTTP/1.1 Host: hello.com Accept: / Content-Type: text/html Content-Length: 17

请求数据...

TourId=3&UserId=1

这与您的控制器如何路由请求有关。你似乎定义了这样的东西

默认获取:

public async Task<IHttpActionResult> MethodName(){ 
  return this.Ok()
}

[HttpGet]
public async Task<IHttpActionResult> MethodName(){ 
  return this.Ok()
}

应该有一些你可以在函数上面定义的属性:

对于POST:

[HttpPost]
public async Task<IHttpActionResult> MethodNamePost(){ 
  return this.Ok()
}

对于 PUT:

[HttpPut]
public async Task<IHttpActionResult> MethodNamePut(){ 
  return this.Ok()
}

就像赢说的那样:

[HttpPut]
[Route("api/sales")]
public object Put([FromBody] Sale sale)
{
    sale.DateTime = DateTime.Now;
    paymentRepository.Insert(sale);
    paymentRepository.Save();

    return new { id = sale.SaleId };
}

不过我会将 return 更改为 this.Ok(new {id = sale.SaleId});

你的请求头是错误的,应该是这样的

{
"UserId":"1",
"TourID":"3",
}

原因:application/json

我真傻,它在寻找防伪令牌。我以为我已经将过滤器注释掉了,但我是为 MVC 而不是 Web Api 做的。哎呀

我还需要将内容类型设置为 application/json 并将数据设置为 { "TourId":"3", "UserId":"1" } 以便模型绑定起作用。