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

前端之家收集整理的这篇文章主要介绍了c# – WebApi2请求的资源不支持post前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我已经阅读了大量描述相同错误消息的类似帖子,但它们似乎与我遇到的情况不符. @H_404_2@我最近开始使用Web API并将我所有的MVC方法删除了我返回JSON等的地方,因此MVC将只渲染html,我将通过webapi控制器的ajax调用模型.

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

@H_404_2@路由

  1. public static void Register(HttpConfiguration config)
  2. {
  3. config.Routes.MapHttpRoute(
  4. name: "DefaultAreaApi",routeTemplate: "api/{area}/{controller}/{action}/{id}",defaults: new { id = RouteParameter.Optional }
  5. );
  6.  
  7. config.Routes.MapHttpRoute(
  8. name: "DefaultApi",routeTemplate: "api/{controller}/{action}/{id}",defaults: new { id = RouteParameter.Optional }
  9. );
  10. }
@H_404_2@调节器

  1. // Returns Model
  2. [HttpGet]
  3. public HttpResponseMessage SelectAgent()
  4.  
  5. // The requested resource does not support http method 'POST'.
  6. [HttpPost]
  7. public HttpResponseMessage SelectAgent(Guid id)
@H_404_2@JQuery的

  1. // Works fine
  2. $.ajax({
  3. 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) {
  4.  
  5. // Works fine
  6. $.getJSON("/api/Account/Users/SelectAgent",function (model) { ....
  7.  
  8. // 405
  9. $.ajax({
  10. type: 'POST',url: '/api/Account/Users/SelectAgent',data: "{'id':'" + selectModel.agentId() + "'}",success: function (response) {....
@H_404_2@传递的数据似乎很好(或者至少是它曾经用过的MVC控制器).

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

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

解决方法

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

@H_404_2@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.)

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

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

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

@H_404_2@public HttpResponseMessage SelectAgent([FromBody] Guid id)

猜你在找的C#相关文章