【发布时间】:2013-12-02 13:59:45
【问题描述】:
我有一个适用于 GET 和 POST 的 .NET MVC RESTful API,但对于 PUT 请求返回 404:
[Authorize]
public class TasksController : ApiController
{
// GET api/tasks
/// <summary>
/// Get all users tasks.
/// </summary>
/// <returns>Task Object (JSON serialised)</returns>
public IEnumerable<Task> Get()
{
List<Task> tasks = new List<Task>();
...
return tasks;
}
// GET api/tasks/5
public Task Get(Int64 id)
{
Task thisTask = new Task();
...
return thisTask;
}
// POST api/tasks
public void Post(Task item)
{
if (item == null)
{
throw new ArgumentNullException("item");
}
...
}
// PUT api/tasks/5
public void Put(Int64 id, Task item)
{
if (item == null)
{
throw new ArgumentNullException("item");
}
...
}
// DELETE api/tasks/5
public void Delete(int id)
{
...
}
// PUT, GET, POST, DELETE api/tasks...
[AllowAnonymous]
public HttpResponseMessage Options()
{
var response = new HttpResponseMessage();
response.StatusCode = HttpStatusCode.OK;
return response;
}
}
知道为什么它不会拾取 PUT 吗? (即使 OPTIONS 也能正常工作)
路由:
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
// Web API routes
config.MapHttpAttributeRoutes();
// CORS Enabled
//var cors = new EnableCorsAttribute("localhost", "*", "*");
//config.EnableCors(cors);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
}
}
Web.Config:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
<add name="Access-Control-Allow-Headers" value="Authorization, Content-Type" />
</customHeaders>
</httpProtocol>
附录看起来它回来的速度是即时的,即使在重新编译之后,所以我猜它甚至没有进入应用程序,所以一定是配置问题。
【问题讨论】:
-
您发送的
PUT请求是什么样的? -
不确定您的意思?我正在使用 Fiddler 进行测试,它看起来与 GET (api/tasks/17) 相同,除了我从 GET 调用中复制的有效负载。
-
听起来你的网络服务器没有启用 PUT,看看这个帖子:stackoverflow.com/questions/10906411/…
-
路由配置是什么?现在
api/tasks/17将在PUT上抛出一个404,因为没有匹配的签名。 -
已从 WebApiConfig 添加路由
标签: c# asp.net api http-status-code-404 restful-url