加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 18:05:09 所属栏目:百科 来源:网络整理
导读:我已经阅读了大量描述相同错误消息的类似帖子,但它们似乎与我遇到的情况不符. 我最近开始使用Web API并将我所有的MVC方法都删除了我返回JSON等的地方,因此MVC将只渲染html,我将通过webapi控制器的ajax调用模型. 这是奇怪的事情,我可以从我的家庭apiControlle
我已经阅读了大量描述相同错误消息的类似帖子,但它们似乎与我遇到的情况不符.

我最近开始使用Web API并将我所有的MVC方法都删除了我返回JSON等的地方,因此MVC将只渲染html,我将通过webapi控制器的ajax调用模型.

这是奇怪的事情,我可以从我的家庭apiController获取和POST(所以我可以登录/注册等),但我只能从我创建的区域中的API控制器获取.我得到了405(方法不允许),即使它的装饰和调用方式与其他控制器相同.我想路由是好的,否则它不会返回我的初始获取?

路由

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

调节器

// 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',data: "{'id':'" + selectModel.agentId() + "'}",success: function (response) {....

传递的数据似乎很好(或者至少是它曾经用过的MVC控制器).

我根本没有修改Home API控制器,我不明白我怎么能发布到那个而不是我的其他控制器.哎呀.

任何正确方向的指针都会很棒.

解决方法

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

您可以在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.)

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

>更改您要提交的网址,以在电子邮件的查询字符串中包含ID

url:’/ api / Account / Users / SelectAgent?id =’selectModel.agentId()
>更改操作签名以读取Id FromBody:

public HttpResponseMessage SelectAgent([FromBody] Guid id)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读