我正在使用基本的CRUD操作处理ASP.NET WebAPI项目。该项目在本地运行,并在Windows Azure中有一个示例数据库。
到目前为止,Http GET和POST工作正常,给我一个200和201.但我正在努力与DELETE和POST。我更改了Web.config中的处理程序,删除了WebDav,但这些都没有用。同时启用CORS和[AcceptVerbs]等各种属性也不起作用。
知道我做错了吗?
Fiddler Raw Output:
HTTP/1.1 405 Method Not Allowed
Cache-Control: no-cache
Pragma: no-cache
Allow: GET
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?QzpcVXNlcnNcTWFyY1xPbmVEcml2ZVxEb2t1bWVudGVcRmlcVnNQcm9qZWt0ZVxONTIwMTQwODI1XE41XE41XGFwaVxwcm9kdWN0XDEwODM=?=
X-Powered-By: ASP.NET
Date: Sun, 14 Sep 2014 15:00:43 GMT
Content-Length: 75
{"Message":"The requested resource does not support http method 'DELETE'."}
的Web.config:
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true">
<remove name="WebDAVModule" />
</modules>
<handlers>
<remove name="WebDAV" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT" type="System.Web.Handlers.TransferRequestHandler" resourceType="Unspecified" requireAccess="Script" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
控制器:
public class ProductController : BaseApiController
{
public ProductController(IRepository<Product> repo)
: base(repo)
{
}
[HttpGet]
public IEnumerable<Product> Get()
{
//...
}
[HttpGet]
public Product Get(int id)
{
//...
}
[HttpPost]
public HttpResponseMessage Post([FromBody] Product product)
{
//...
}
[HttpPut]
public HttpResponseMessage Put(int productId, [FromBody] Product product)
{
//..
}
[HttpDelete]
public HttpResponseMessage Delete(int productId)
{
//..
}
}
路由&amp;格式化器:
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));
config.Routes.MapHttpRoute(
name: "Product",
routeTemplate: "api/product/{id}",
defaults: new {controller = "product", id = RouteParameter.Optional }
);
// Custom Formatters:
config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(
config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml"));
var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
}
}
答案 0 :(得分:26)
最后我发现了我搞砸了什么。两种控制器方法(Post和Put)中Id(productId)的命名必须与自定义路由(id)中的命名相同。当我将它从productId更改为id时,POST和PUT都在fiddler中工作。之后,我将Web.config设置切换回默认设置。这是我改变的:
控制器:
[HttpPut]
public HttpResponseMessage Put(int id, [FromBody] Product product)
{
//..
}
[HttpDelete]
public HttpResponseMessage Delete(int id)
{
//..
}
的Web.config:
<system.webServer>
<modules>
<remove name="FormsAuthentication" />
</modules>
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
答案 1 :(得分:10)
ASP.NET Web API 2中的&#34;属性路由&#34; (2014年1月20日)文章告诉我们以下内容;
路由是Web API将URI与操作匹配的方式。 Web API 2支持 一种新的路由,称为属性路由。
(参见:"Attribute Routing in ASP.NET Web API 2")
因此,从Web API 2开始,您还可以通过使用您希望命名的占位符添加路径属性[到相关方法]来修复它。
[HttpDelete]
[Route("api/product/{productId}")]
public HttpResponseMessage Delete(int productId)
{
if (values.Count > productId) {
values.RemoveAt(productId);
}
}
在我自己的代码中测试过,因为我遇到了同样的问题,它就像一个魅力!
答案 2 :(得分:0)
尝试在您的WebConfig文件中添加以下代码:
<system.webServer>
<handlers>
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
我也遇到了同样的问题,这样做解决了!