PUT和Delete不使用ASP。NET WebAPI和Windows Azure上的数据库

时间:2022-11-05 11:12:16

I'm working on a ASP.NET WebAPI project with basic CRUD operations. The project runs locally and has a sample database living inside Windows Azure.

我在做ASP。具有基本CRUD操作的WebAPI项目。该项目在本地运行,在Windows Azure中有一个示例数据库。

So far, the Http GET and POST works fine, giving me a 200 and 201. But I'm struggling with DELETE and POST. I changed the handlers in the Web.config, removed WebDav, but none of this worked. Also enabling CORS and all sorts of Attributes like [AcceptVerbs] didn't work.

到目前为止,Http GET和POST工作正常,给了我200和201。但我正在努力删除和张贴。我更改了Web中的处理程序。配置,删除WebDav,但这些都不起作用。同样,启用CORS和诸如[accept动词]之类的各种属性也不起作用。

Any idea what I am doing wrong?

知道我做错了什么吗?

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:

. 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>

Controller:

控制器:

 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)
        {
            //..
        }

    }

Routing & Formatters:

路由和格式器:

 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();
    }
}

2 个解决方案

#1


26  

Finally I found what I messed up. The naming of the Id (productId) in both controller methods (Post and Put) must be the same as in the customized routing (id). When I changed it from productId to id both POST and PUT worked in fiddler. After that I switched back my Web.config settings to the default one. This is what I changed:

最后我找到了我搞砸的东西。在两个控制器方法(Post和Put)中,Id (productId)的命名必须与自定义路由(Id)相同。当我把它从productId更改为id和POST,然后放到fiddler中。在那之后,我就把我的网络换回来了。配置设置为默认设置。这就是我改变的:

Controller:

控制器:

    [HttpPut]
    public HttpResponseMessage Put(int id, [FromBody] Product product)
    {
        //..
    }

    [HttpDelete]
    public HttpResponseMessage Delete(int id)
    {
        //..
    }

Web.config:

. 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>

#2


9  

The "Attribute Routing in ASP.NET Web API 2" (20-Jan-2014) article tells us the following;

在ASP中的属性路由。NET Web API 2”(20-Jan-2014)文章告诉我们:

Routing is how Web API matches a URI to an action. Web API 2 supports a new type of routing, called attribute routing.

路由是Web API将URI与操作匹配的方式。Web API 2支持一种新的路由类型,称为属性路由。

( See: "Attribute Routing in ASP.NET Web API 2" )

(参见:“ASP中的属性路由。NET Web API 2")

So, as of Web API 2, you can also fix it by adding the route attribute [to the method in question] with the placeholder named as you wish.

因此,在Web API 2中,您还可以通过添加route属性(到相关方法)和您希望的占位符来修复它。

[HttpDelete]
[Route("api/product/{productId}")]
public HttpResponseMessage Delete(int productId)
{
    if (values.Count > productId) {
        values.RemoveAt(productId);
    }
}

Tested this in my own code, because I got hit with the same problem, and it worked like a charm!

在我自己的代码中测试了这个,因为我遇到了同样的问题,而且它运行得非常棒!

#1


26  

Finally I found what I messed up. The naming of the Id (productId) in both controller methods (Post and Put) must be the same as in the customized routing (id). When I changed it from productId to id both POST and PUT worked in fiddler. After that I switched back my Web.config settings to the default one. This is what I changed:

最后我找到了我搞砸的东西。在两个控制器方法(Post和Put)中,Id (productId)的命名必须与自定义路由(Id)相同。当我把它从productId更改为id和POST,然后放到fiddler中。在那之后,我就把我的网络换回来了。配置设置为默认设置。这就是我改变的:

Controller:

控制器:

    [HttpPut]
    public HttpResponseMessage Put(int id, [FromBody] Product product)
    {
        //..
    }

    [HttpDelete]
    public HttpResponseMessage Delete(int id)
    {
        //..
    }

Web.config:

. 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>

#2


9  

The "Attribute Routing in ASP.NET Web API 2" (20-Jan-2014) article tells us the following;

在ASP中的属性路由。NET Web API 2”(20-Jan-2014)文章告诉我们:

Routing is how Web API matches a URI to an action. Web API 2 supports a new type of routing, called attribute routing.

路由是Web API将URI与操作匹配的方式。Web API 2支持一种新的路由类型,称为属性路由。

( See: "Attribute Routing in ASP.NET Web API 2" )

(参见:“ASP中的属性路由。NET Web API 2")

So, as of Web API 2, you can also fix it by adding the route attribute [to the method in question] with the placeholder named as you wish.

因此,在Web API 2中,您还可以通过添加route属性(到相关方法)和您希望的占位符来修复它。

[HttpDelete]
[Route("api/product/{productId}")]
public HttpResponseMessage Delete(int productId)
{
    if (values.Count > productId) {
        values.RemoveAt(productId);
    }
}

Tested this in my own code, because I got hit with the same problem, and it worked like a charm!

在我自己的代码中测试了这个,因为我遇到了同样的问题,而且它运行得非常棒!