gpt4 book ai didi

c# - WebApi2 请求的资源不支持post

转载 作者:太空狗 更新时间:2023-10-29 20:54:38 24 4
gpt4 key购买 nike

我已经阅读了大量描述相同错误消息的类似帖子,但它们似乎与我遇到的情况不符。

我最近开始使用 Web API 并将我所有的 MVC 方法从我返回 JSON 等的地方删除,所以 MVC 将只呈现 html,我将通过我的 webapi Controller 中的 ajax 调用模型。

奇怪的是,我可以从我的 Home apiController 进行 GET 和 POST(这样我就可以登录/注册等),但我只能从我创建的区域中的 API Controller 进行 GET。我得到一个 405(方法不允许),即使它的装饰和调用方式与其他 Controller 相同。我想路由没问题,否则它不会返回我的初始 get?

路由

 public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultAreaApi",
routeTemplate: "api/{area}/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);

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

Controller

 // Returns Model
[HttpGet]
public HttpResponseMessage SelectAgent()

// The requested resource does not support http method 'POST'.
[HttpPost]
public HttpResponseMessage SelectAgent(Guid id)

JQuery

 // Works fine
$.ajax({
type: 'POST',
url: '/api/Home/Login',
headers: options.headers,
contentType: "application/json; charset=utf-8",
dataType: 'JSON',
data: ko.toJSON(self.serverModel),
success: function (response) {

// Works fine
$.getJSON("/api/Account/Users/SelectAgent", function (model) { ....

// 405
$.ajax({
type: 'POST',
url: '/api/Account/Users/SelectAgent',
headers: options.headers,
contentType: "application/json; charset=utf-8",
dataType: 'JSON',
data: "{'id':'" + selectModel.agentId() + "'}",
success: function (response) {....

传递的数据看起来很好(或者至少它是针对它过去使用的 MVC Controller )。

我根本没有修改 Home API Controller ,我不明白我怎么能发布到它而不是我的其他 Controller 。啊。

任何指向正确方向的指示都会很棒。

最佳答案

Web API 仅查看基本数据类型的查询字符串参数。因此,当您发帖时,您的帖子只是查看 /api/Account/Users/SelectAgent 的 url。与函数匹配时不考虑提交的数据,因为您没有使用 [FromBody] 属性标记 Guid。因此返回“不允许的方法”错误,因为它正在将您的 POST 请求发送到您的 GET 方法(无参数)。

您可以在 asp.net 上阅读更多相关信息:

If the parameter is a “simple” type, Web API tries to get the value from the URI. Simple types include the .NET primitive types (int, bool, double, and so forth), plus TimeSpan, DateTime, Guid, decimal, and string, plus any type with a type converter that can convert from a string. (More about type converters later.)

要解决此问题,请尝试执行以下操作之一:

  1. 更改您提交的 url 以在电子邮件的查询字符串中包含 id

    url: '/api/Account/Users/SelectAgent?id=' + selectModel.agentId()

  2. 更改 Action 签名以读取 Id FromBody:

    public HttpResponseMessage SelectAgent([FromBody]Guid id)

关于c# - WebApi2 请求的资源不支持post,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21905023/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com