【问题标题】:Method not allowed doing a post in WebAPI不允许在 WebAPI 中发帖的方法
【发布时间】:2015-11-03 16:40:19
【问题描述】:
I have a controller defined as follows

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace MissingClinics.Controllers
{
    [RoutePrefix("api/appointment")]
    public class AppointmentController : ApiController
    {
        [HttpPost]
        public IHttpActionResult GetMissingKeys([FromBody]String MRNList)
        {
            return Ok();
        }
    }
}

以下 JavaScript 调用该页面。

            try {
                $.ajax({
                    type: 'POST',
                    url: '/api/Appointment/GetMissingKeys',
                    data: $('#mrnList').val(),
                    dataType: 'text'
                }).done(function () {
                    alert('done!');
                }).fail(function (Status, errorThrown) {
                    alert('Error: ' + Status.status + ' - ' + Status.statusText);
                }).always(function () {
                    alert('All done or not');
                });
            }
            catch (e) {
                alert(e);
            }

WebApi.config 如下

namespace MissingClinics
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

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

RouteConfig.cs

namespace MissingClinics
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }
    }
}

现在因为我要传递大量数据,所以我需要在正文中传递它(而不是作为 URL 的一部分)。

但在调用中它返回错误 405 - 方法不允许。但从我所见,jquery 应该发出一个 post 请求并且控制器正在接受一个 post - 那么为什么不允许该方法?

【问题讨论】:

  • 您的请求数据中是否有 HTML,如果有,请在您的参数中使用 [AllowHtml] 属性。
  • 不确定属性路由是否会默认为您的方法名称...在您的方法上尝试[Route("GetMissingKeys")]。
  • 没有 HTML,我也尝试过路由属性
  • @PaulSChapman 您是否尝试排除 dataType: 'text' 属性或指定其他类型,如“应用程序/json”等?您是否也尝试过使用 Fiddler 或 Chrome 浏览器的 Advanced Rest Client 等调试工具访问 api 并查看发生了什么?
  • 这完全是猜测,但可能是 WebAPI 混淆了它的约定,因为您的方法以 Get 为前缀。我必须检查来源才能确定。

标签: javascript c# jquery asp.net-web-api


【解决方案1】:

使用默认路由模板,Web API 使用 HTTP 方法来选择操作。但是,您也可以创建一个路由,其中​​操作名称包含在 URI 中:

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

Routing instructions

【讨论】:

  • 我已经尝试过了——甚至颠倒了 Route 和 HttpPost 的顺序——甚至尝试了 AcceptVerb
  • @PaulSChapman 您能否将您的 Startup 类实现添加到您的主题中?会尝试找出问题所在。
  • @PaulSChapman 我已经更改并在我的答案中添加了一些附加信息。在文章末尾,您可以找到有关以下内容的信息:按操作名称路由。看看这个。
【解决方案2】:

自从我使用 jquery 以来已经有一段时间了,但是

不应该这样

data: $('#mrnList').val(),

就这样

data : {mrnList: $('#mrnList').val()}, //Or MrnList depending on your jsonformatting options

我认为数据类型也应该是'json'。

您是否尝试将[Route("GetMissingKeys")] 添加到您的方法中?

【讨论】:

    【解决方案3】:

    您是否将默认路由从api/{action} 更改为api/{controller}/{action}/{id}?

    ASP.NET WEB API select action with request HTTP方法,有以下两种方式:

    1.更改web api默认路由

    WebApiConfig.cs

    config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } );
    有了这个,你不需要改变你的 html 文件。

    2.更改你的动作名称

    public IHttpActionResult Post([FromBody]String MRNList)

    并像这样调用javascript:

    $.ajax("/api/Appointment", {type:"POST", data:$("").val() ... }

    【讨论】:

    • 不确定您的意思,但确实尝试更改 RouteConfig.cs 中的 url,但这似乎没有什么不同
    猜你喜欢
    • 2016-05-06
    • 2016-12-03
    • 2014-05-21
    • 1970-01-01
    • 2019-09-22
    • 2015-08-03
    • 2014-06-21
    • 2021-07-28
    • 1970-01-01
    相关资源
    最近更新 更多