我已经阅读了大量描述相同错误消息的类似帖子,但它们似乎与我遇到的情况不符.
@H_404_2@我最近开始使用Web API并将我所有的MVC方法都删除了我返回JSON等的地方,因此MVC将只渲染html,我将通过webapi控制器的ajax调用模型.
@H_404_2@这是奇怪的事情,我可以从我的家庭apiController获取和POST(所以我可以登录/注册等),但我只能从我创建的区域中的API控制器获取.我得到了405(方法不允许),即使它的装饰和调用方式与其他控制器相同.我想路由是好的,否则它不会返回我的初始获取?
@H_404_2@路由
@H_404_2@调节器
- 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 }
- );
- }
@H_404_2@JQuery的
- // Returns Model
- [HttpGet]
- public HttpResponseMessage SelectAgent()
- // The requested resource does not support http method 'POST'.
- [HttpPost]
- public HttpResponseMessage SelectAgent(Guid id)
@H_404_2@传递的数据似乎很好(或者至少是它曾经用过的MVC控制器). @H_404_2@我根本没有修改Home API控制器,我不明白我怎么能发布到那个而不是我的其他控制器.哎呀. @H_404_2@任何正确方向的指针都会很棒.
- // 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) {....
解决方法
Web API仅查看基本数据类型的查询字符串参数.因此,当您发布帖子时,您的帖子只是查看/ api / Account / Users / SelectAgent的网址.在与函数匹配时,不会考虑提交的数据,因为您没有使用[FromBody]属性标记Guid.因此,正在返回“Method Not Allowed”错误,因为它正在向您的GET方法发送POST请求(无params).
@H_404_2@您可以在asp.net上阅读更多相关信息:
>更改操作签名以读取Id FromBody: @H_404_2@public HttpResponseMessage SelectAgent([FromBody] Guid id)
@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)