删除http:// localhost:54178 / api / employees 405(不允许使用方法)

问题描述 投票:0回答:2

我正在使用带有C#WEB API的React Client。

REACT功能

 const deleteThisEmployee = empId => {
    const formData = new FormData();
    formData.append("id", empId);
    fetch("http://localhost:54178/api/employee", {
      method: "DELETE",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json"
      },
      body: formData
    })
      .then(resp => resp.json())
      .then(
        result => {
          // SUCCESS
        }
        // FAIL
      );
  };

WEB API设置:

   public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {          
            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            // add this to support JSON response and not XML
            config.Formatters.JsonFormatter.SupportedMediaTypes
                .Add(new MediaTypeHeaderValue("text/html"));

            // Enable Cors

            config.EnableCors(new EnableCorsAttribute("http://localhost:3000", "*", "*"));  // React
        }
    }

和控制器:

public class EmployeeController : ApiController
{
    // .. Some other verbs

    public String Delete(int id)
    {
        // TODO
        Console.WriteLine("Got the Employee ID : " + id);

        // Continue with delete logic 
    }

}

[当我尝试删除一行时,我不断得到

DELETE http://localhost:54178/api/employee 405 (Method Not Allowed)

我已经检查了关于SO的一些问题,建议在WEB.Config中添加

  <remove name="WebDAV" />
  <remove name="WebDAVModule" />

但是没有帮助。

任何想法可能导致此问题吗?

asp.net reactjs asp.net-web-api asp.net-web-api2 asp.net-core-webapi
2个回答
2
投票

可能是几件中的一件(或全部)。>>

  1. 该路线未自动注册为DELETE。您可以通过在[HttpDelete]操作上方使用Delete添加来解决此问题。
  2. 它不是在寻找体内的id。根据规范,DELETE方法may contain a body并不意味着ASP.NET支持它。 (我不记得它是否有用)。您可以尝试通过URL而不是在正文中传递它:
  3.  const deleteThisEmployee = empId => {
        fetch("http://localhost:54178/api/employee?id=" + empId, {
          method: "DELETE",
          headers: {
            Accept: "application/json",
            "Content-Type": "application/json"
          }
        })
          .then(resp => resp.json())
          .then(
            result => {
              // SUCCESS
            }
            // FAIL
          );
      };
    

1
投票

您应该告诉框架在控制器上寻找具有动作动词属性的删除方法,如下所示:

© www.soinside.com 2019 - 2024. All rights reserved.