问题描述
我被Web API 2控制器困住了,从中我调用 PUT
方法,它给我一个错误,提示不允许使用该方法.我在 Web.config
中添加了几行代码,以防止WebDAV阻塞方法.我尝试了一切,但没有用.控制器中的 PUT
方法可能是问题.
I am stuck with Web API 2 controller, from which I call PUT
method and it gives me an error that method isn't allowed. I added lines of code in Web.config
that prevent WebDAV to block methods. I tried everything but it is not working. It is probably problem with my PUT
method in a controller.
这是我的控制器代码:
public IHttpActionResult Put(int id, [FromBody]ArticleModel model) {
var article = _articleService.UpdateArticle(model);
return Ok<ArticleModel>(article);
}
这是我称之为put的代码:
This is a code from where I call put :
response = await client.PutAsJsonAsync("api/article/2", articleModel);
在此代码之前,我将客户端定义为http并添加了所需的属性,并调用了其他控制器方法(GET,POST,DELETE),它们都可以工作.这是从Windows Form应用程序发出的,我也从Postman打电话,但仍然是相同的错误.
before this code I defined client as http and added needed properties, and called other controller methods (GET, POST, DELETE) , they all work. This is from Windows Form app, and I am also calling from Postman but still the same error.
推荐答案
添加 [HttpPut]
, [RoutePrefix("api/yourcontroller")]
和[Route("put")]
属性分配给您的控制器方法
Add [HttpPut]
, [RoutePrefix("api/yourcontroller")]
and [Route("put")]
attribute to your controller method
示例:
[RoutePrefix("api/yourcontroller")]
public class YourController
{
[HttpPut]
[Route("{id}/put")]
public IHttpActionResult Put(int id, [FromBody]ArticleModel model) {
var article = _articleService.UpdateArticle(model);
return Ok<ArticleModel>(article);
}
}
编辑1
public class YourController
{
[HttpPut]
[Route("api/article/{id}/put")]
public async Task<HttpResponseMessage> Put(int id, [FromBody]ArticleModel model) {
var article = _articleService.UpdateArticle(model);
return Ok<ArticleModel>(article);
}
}
从您的HttpRequest调用看来,似乎应该是 HttpResponseMessage
,因此将返回类型更改为 async Task< HttpResponseMessage>
From your HttpRequest call It seems what is expected is a HttpResponseMessage
So changed the return type to async Task<HttpResponseMessage>
用于创建HttpRequest的代码:
Code for making HttpRequest:
response = await client.PutAsJsonAsync("api/article/2/put", articleModel);
这篇关于Web API 2-现在允许使用方法(405)进行PUT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!