【发布时间】:2014-07-23 07:25:58
【问题描述】:
我已经阅读了here 和here 的建议,但无法让它发挥作用。我是 WebApi 的新手,已经让它为 GET 工作,但无法执行 PUT。
首先我应该注意,我还没有在 IIS 中托管 thw api,只是直接从 VS 本地调试。有问题吗?
谁能发现我可能做错了什么或错过了什么?我正在使用 WebApi2 并安装了 CORS 和 AttributeRouting。正如建议的那样,我打算卸载 WebDav,但在任何地方都找不到它,所以我认为我在那里没问题。
所以,这里是代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using BLL = MyApp.BLL;
using MyApp.ObjectModel;
using System.Web.Http.Cors;
using AttributeRouting.Web.Http;
namespace MyApp.Web.Controllers
{
[EnableCors("*", "*", "GET,POST,PUT,DELETE")]
public partial class PersonController: ApiControllerBase
{
private readonly BLL.Person PersonBll;
public PersonController()
{
PersonBll = new BLL.Person();
}
// GET api/PersonBrief/5
//[Route("api/PersonBrief/{id}")]
public Person GetBrief(int id)
{
return PersonBll.GetBrief(id);
}
// GET api/Person/5
//[Route("api/Person/{id}")]
public Person Get(int id)
{
return PersonBll.Get(id);
}
// POST api/Person
public Person Post(Person Person)
{
return PersonBll.Add(Person);
}
// PUT api/Person
public IHttpActionResult Put(Person Person)
{
try
{
PersonBll.Update(Person);
return Ok<int>(Person.PersonID);
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
// DELETE api/Person
public void Delete(int id)
{
PersonBll.Deactivate(id);
}
}
}
GET 工作正常,但 PUT 在从 Chrome 的 PostMan 尝试时会出现此错误: "Message": "请求的资源不支持 http 方法 'PUT'。"
这里是 WebApiConfig...
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API routes
config.MapHttpAttributeRoutes();
// Convention-based routing.
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
config.EnableCors();
}
}
如果需要更多信息,我很乐意更新详细信息。我的猜测是我错过了一些真正的重要概念或其他东西:) 非常感谢任何帮助,我会标记正确的答案。
更新 1::
好的,所以在玩了很多之后,我能够确定 PUT 何时工作和不工作......我已经更新了上面的控制器代码,以便它包含所有细节。基本上,我发现如果我删除了放在 Get 和 GetBrief 方法上的 AttributeRouting(例如:[Route("api/PersonBrief/{id}")]),我就能够成功地将 POST、PUT 和 DELETE 发送到控制器中!但我显然将这些属性添加到 Get 和 GetBrief 方法中,以便我可以点击它们。如果没有属性,我会得到模棱两可的错误,因为它不知道要命中哪个。为什么是那些导致问题的人,我该如何解决这个问题?
【问题讨论】:
-
您在 VS 中本地运行,但它不是自托管的,对吗?然后,您可能希望按照stackoverflow.com/questions/10906411 和stackoverflow.com/questions/11155528 中的详细说明更新 web.config
-
这可能是服务器配置和应用程序相关的问题。
标签: rest url-routing cors asp.net-web-api2