【问题标题】:ASP.NET WebApi : (405) Method Not AllowedASP.NET WebApi:(405)方法不允许
【发布时间】:2016-05-06 01:24:31
【问题描述】:

我有一个 Web Api 控制器。它的行为非常奇怪。当我使用 PostMan 时,我可以访问 Web Api 上的 POST 方法,但是当我从 .net 使用 HttpWebRequest 时,它返回 (405) Method Not Allowed。 我把Web Api代码放在这里:

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

namespace MyProject.Controllers
{
    public class TestController : ApiController
    {
        [HttpPost]
        public int buy(OrderResult value)
        {
            try
            {
                if (value.InvoiceDate != null && value.Result == 1)
                {
                    return 0;
                }
            }
            catch{}

            return -1;
        }
    }

    public class OrderResult
    {
        public int Result { get; set; }
        public long InvoiceNumber { get; set; }
        public string InvoiceDate { get; set; }
        public long TimeStamp { get; set; }
    }
}

这是我的 WebApiConfig.cs:

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

namespace MyProject
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {

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

        }
    }
}

这是我从另一个 .NET 项目发送 POST 请求的方式:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;

namespace MyProject.Controllers
{
    public static class WebReq
    {
        public static string PostRequest(string Url, string postParameters)
        {
            try
            {
                HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(Url);
                myReq.Method = "POST";
                myReq.Timeout = 30000;
                myReq.Proxy = null;

                byte[] postData = Encoding.UTF8.GetBytes(postParameters);
                myReq.ContentLength = postData.Length;
                myReq.ContentType = "application/x-www-form-urlencoded";
                using (Stream requestWrite = myReq.GetRequestStream())
                {
                    requestWrite.Write(postData, 0, postData.Length);
                    requestWrite.Close();
                    using (HttpWebResponse webResponse = (HttpWebResponse)myReq.GetResponse())
                    {
                        if (webResponse.StatusCode == HttpStatusCode.OK)
                        {
                            using (Stream str = webResponse.GetResponseStream())
                            {
                                using (StreamReader sr = new StreamReader(str))
                                {
                                    return sr.ReadToEnd();
                                }
                            }
                        }
                        return null;
                    }
                }
            }
            catch (Exception e)
            {
                var message = e.Message;
                return null;
            }
        }

    }
}

我已经在我的 web.config 中添加了以下代码:

<modules runAllManagedModulesForAllRequests="true">
  <remove name="WebDAVModule" />
</modules>

这很奇怪,因为我可以从 PostMan 成功发送 POST 请求。 PostMan 将此代码发送到 API。

POST /api/Test/buy HTTP/1.1
Host: domain.com
Cache-Control: no-cache
Postman-Token: 9220a4e6-e707-5c5f-ea61-55171a5dd95f
Content-Type: application/x-www-form-urlencoded

InvoiceDate=28012016&Result=1

我将不胜感激任何解决问题的建议。

【问题讨论】:

    标签: asp.net asp.net-mvc asp.net-web-api


    【解决方案1】:
         byte[] postData = Encoding.UTF8.GetBytes(postParameters);
                myReq.ContentLength = postData.Length;
                myReq.ContentType = "application/x-www-form-urlencoded";
                using (Stream requestWrite = myReq.GetRequestStream())
                {
                    requestWrite.Write(postData, 0, postData.Length);
    

    您很可能没有发送正确的 x-www-form-urlencoded 请求。您可能无法从作为 postParameters 传入的任何内容中正确编码数据。见Post form data using HttpWebRequest

    由于您没有根据 x-www-form-urlencoded 生成有效的 OrderResult 对象,因此路由选择器不会选择您的 Buy 操作。这就是为什么你得到 POST 是不允许的。

    如果您更改了OrderResult value = null,您可能会访问控制器,因为它现在是一个可选参数。但是,这不是您想要的,除非您将拥有一个奇怪的控制器,其行为如下:

    Buy(OrderResult value = null)
    {
        if(value== null)
            value = MyCustomDeserializeFromRequestBody(RequestContext)
    
        ...
    }
    

    最终你真的不应该使用这个类,因为我想到了现代开发的更好的构造https://stackoverflow.com/a/31147762/37055https://github.com/hhariri/EasyHttp

    【讨论】:

      【解决方案2】:

      用提琴手或类似的东西捕捉你的请求,你可能正在发送“OPTIONS”方法。

      这与 CORS 有关,所以我认为您的解决方案是在 WebAPI 上启用 Cors

      http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

      【讨论】:

      • 这不是 CORS 问题,这实际上是我的第一个想法,但 OP 纯粹从服务器/应用程序运行,而不是在浏览器+ajax 中运行。
      【解决方案3】:

      我找到了解决方案。

      我检查了 Fiddler 的请求。当我向 API 发送 POST 请求时,它会使用这个新参数 AspxAutoDetectCookieSupport=1 自动重定向到相同的地址

      How to remove AspxAutoDetectCookieSupport=1

      最后我把web.config中的cookieless="AutoDetect"改成了cookieless="UseCookies",问题就解决了。

      【讨论】:

        【解决方案4】:

        我知道这是一篇旧帖子,但也许这可能对其他人有所帮助。我刚刚遇到了类似的问题,当我清楚地在邮递员中发帖时收到 405 错误“不允许”。结果,我使用 http 而不是 https 提交到 URL。更改为 https 修复它。

        【讨论】:

        • 简单明了。谢谢保罗。
        【解决方案5】:

        在我的情况下,我在项目中有一个与路由同名的物理文件夹(例如沙盒),并且任何 POST 请求都被 IIS 中的静态文件处理程序(显然)拦截,而不是 WebAPI 运行时。

        得到一个误导性的 405 错误,而不是更预期的 404,这是我花了一些时间进行故障排除的原因。

        不容易陷入这种情况,但有可能。希望它可以帮助某人。

        【讨论】:

        • 谢谢,这发生在我身上,完全不明显,不知道没有这个建议我怎么会找到它。
        猜你喜欢
        • 1970-01-01
        • 2019-09-22
        • 2016-12-03
        • 2019-07-28
        • 2014-05-21
        • 1970-01-01
        • 1970-01-01
        • 2014-06-21
        • 2021-07-28
        相关资源
        最近更新 更多