【问题标题】:Asp.Net Core 3.1 405 Method Not AllowedAsp.Net Core 3.1 405 方法不允许
【发布时间】:2020-07-06 02:15:39
【问题描述】:

大家好,我需要帮助.. 我总是收到 405 Method Not Allowed

我使用的是 Asp.Net Core Web Application 3.1,HttpGet 没有问题,但是当我使用 HttpPost 时,它总是返回 405 状态码

这是我的控制器

[Route("api/[controller]")]
[ApiController]
public class ExamController : ControllerBase
{
    [HttpPost("PostValue")]
    public ActionResult<HttpResponseMessage> PostInfo([FromBody] PersonalInfo info)
    {
        string json = JsonConvert.SerializeObject(info);
        HttpClient client = new HttpClient();
        var response = client.PostAsync("https://sampleapi/receive", new StringContent(json, Encoding.UTF8, "application/json"));

        if (response.IsFaulted)
            return BadRequest(response);

        return Ok(response);
    }
}

这是我的创业班

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllers();
        services.AddCors(c =>
        {
            c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin());
        });
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseStatusCodePages();

        app.UseHttpsRedirection();

        app.UseRouting();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });

        app.UseCors(options => options.AllowAnyOrigin());
    }

Here is the sample image of URL and the Result

【问题讨论】:

  • 您的操作是POST,所以要访问它,您需要使用HTTP POST方法,在浏览器中点击URL时的默认方法是HTTP GET。

标签: c# asp.net-core-webapi


【解决方案1】:

查看提供的图像,您使用 chrome 发出 url 请求,这是一个 HTTP GET 命令。因此,您的应用程序获得了 HTTP GET 命令,但您的方法想要接受 HTTP POST 方法。这就是为什么它说“方法不允许”。

如果你想尝试http命令,你需要一个web测试工具,比如PostMan。

【讨论】:

    【解决方案2】:

    除了postman测试方法外,另一种测试post请求的方法是到use ajax to send post request in jquery,这里是一个示例:

            <script>
                $(function () {
                    $("#send").click(function () {
                        var personalInfo = { Id:  $('#Id').val(), Name: $('#Name').val() };
                        $.ajax({
                            url: 'http://localhost:50855/api/Exam/PostValue',
                            type: 'POST',
                            contentType: "application/json; charset=utf-8",
                            dataType: 'json',
                            data: JSON.stringify(personalInfo),
                            //success: function (data, textStatus, xhr) {
                            //    console.log(data);
                            //},
                            //error: function (xhr, textStatus, errorThrown) {
                            //    console.log('Error in Operation');
                            //}
                        });
                    });
                })
            </script>
    
       <form id="form1">
            Id : <input type="text" name="Id" id="Id" />
            Name: <input type="text" name="Name" id="Name" />
            <input type="button" id="send" value="Send Post Data" />
        </form>
    

    这是测试结果:

    【讨论】:

      【解决方案3】:

      我只是将我的问题和解决方案添加到此线程中,以防其他人偶然发现此问题。

      我收到了 405 错误代码,尽管该操作使用 HttpPost 和 ValidateAntiForgeryToken 属性进行修饰,并确保发布的表单数据包含防伪令牌。在本地一切正常,但是当我将所有内容都放在服务器上时,我就开始收到 405 错误。原来这个错误与我在我的应用程序中所做的无关。这实际上是我的 MySQL 数据库中的存储过程中的一个问题。在本地,区分大小写不是问题,但在服务器上,我将小写表的名称大写,这导致错误冒泡并给我这个非常模糊的 405 错误。

      我想这里学到的教训是检查一切:)

      编辑:为清楚起见,我的问题与 MySQL 和 Linux 托管有关。不确定如果使用 Windows 托管解决方案是否同样适用

      【讨论】:

        【解决方案4】:

        正确配置 CORS 中间件。在options.AllowAnyOrigin() 之后添加.AllowAnyMethod() 作为链。出于测试目的,您最终可能会这样做:app.UseCors(x =&gt; x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());

        作为另一种选择,请确保您的 Web 服务器(可能是 IIS)除了 GET 之外还允许使用 POST HTTP 方法。

        【讨论】:

          【解决方案5】:

          好的,我一直在阅读有关通过输入 web.config 来删除 WebDav 的信息,但这对我来说不适用于 core 3.1。您需要做的是通过以下方式将其从 IIS 中删除:

          1. 在 IIS 8 中扩展服务器
          2. 选择网站
          3. 点击处理映射(对于站点而不是服务器)
          4. 搜索 WebDav 并将其删除。
          5. 重启 IIS

          Web.config 应该单独放置。当我添加 remove name=WebDav 时,我的 API 停止工作。

            <handlers>
              <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
            </handlers>
          

          注意:如果这不起作用,您可能还需要从服务器中删除它,因为我在进行故障排除时首先删除了它。

          【讨论】:

          • 我在 IIS (Windows 10 Pro) 的站点处理程序映射列表中找不到 WebDav。
          【解决方案6】:

          在控制器的方法头部添加[Route("MethodName")]。就像:

          [Route("api/[controller]")]    
          [ApiController]
          public class AccountController : Controller
          {
              [Route("getusers")]
              public async Task<User> GetUsers()
              {
                  ...
              }
          }
          

          【讨论】:

            猜你喜欢
            • 2019-05-18
            • 2019-09-22
            • 2021-02-14
            • 2019-07-28
            • 2021-09-30
            • 2016-05-06
            • 2018-02-04
            • 1970-01-01
            • 2022-01-15
            相关资源
            最近更新 更多