我正在使用带有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" />
但是没有帮助。
任何想法可能导致此问题吗?
可能是几件中的一件(或全部)。>>
DELETE
。您可以通过在[HttpDelete]
操作上方使用Delete
添加来解决此问题。id
。根据规范,DELETE
方法may contain a body并不意味着ASP.NET支持它。 (我不记得它是否有用)。您可以尝试通过URL而不是在正文中传递它: 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
);
};
您应该告诉框架在控制器上寻找具有动作动词属性的删除方法,如下所示: