【发布时间】:2026-01-03 17:35:02
【问题描述】:
当我使用 fetch (JavaScript API) 将 JavaScript 中的 POST 请求发送到同一项目中的 C# API 时,我收到异常错误消息:erro 405 HTTP 方法(GET、PUT、POST 或 DELETE)对于给定的资源 URI 无效。
'GET' 请求正常运行!但是其他请求方法返回错误。
JavaScript POST 函数
var url = "api/cliente";
await fetch(url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(cliente)
})
.then(response => alert(response.status))
.then(() => getItems())
.catch(error => alert(error));
C# 控制器 GET 和 POST 方法
// GET Method
public object Get(string name, string id)
{
Cliente.cpf = id.ToString();
Cliente.nome = name;
Cliente.loadCliente();
return Cliente;
}
//'POST' Method api/<controller>
public void post (string value)
{
string teste = value;
}
WebAPIConfig:
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Formatters.Remove(config.Formatters.XmlFormatter);
config.Formatters.JsonFormatter.Indent= true;
}
路由器配置:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { action = "Index", id = UrlParameter.Optional }
);
}
【问题讨论】:
-
请英文。整个网站只有英文版。你为什么用另一种语言问?另外:欢迎来到*。我推荐taking the tour,以及阅读how to ask a good question 和what's on topic。
-
对不起,Franz,我已经编辑过了。谢谢。
-
谢谢你。我仍然推荐阅读我链接到的文章。
-
方法名没有任何意义;更清晰地使用属性来指定方法是 GET 还是 POST
-
另外,如果客户端是一个复杂的对象,可以使用[frombody]属性捕获。
标签: javascript c# rest asp.net-web-api