简体   繁体   English

Asp.Net Core 3.1 405 方法不允许

[英]Asp.Net Core 3.1 405 Method Not Allowed

Hi Guys I need help.. I always get 405 Method Not Allowed嗨,伙计们,我需要帮助.. 我总是得到 405 Method Not Allowed

I'm using Asp.Net Core Web Application 3.1, I dont have problem with HttpGet but when i use HttpPost it always return 405 Status Code我正在使用 Asp.Net Core Web Application 3.1,我对 HttpGet 没有问题,但是当我使用 HttpPost 时,它总是返回 405 状态码

Here is the My Controller这是我的 Controller

[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 is my Startup Class这是我的启动 Class

    // 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这是 URL 的示例图像和结果

Looking at the provided image, you use chrome to issue the url request, which is a HTTP GET command.查看提供的图像,您使用 chrome 发出 url 请求,这是一个 HTTP GET 命令。 So, your app got an HTTP GET command but your method wants to accept an HTTP POST method.因此,您的应用程序获得了一个 HTTP GET 命令,但您的方法想要接受一个 HTTP POST 方法。 That's why it says 'method not allowed'.这就是为什么它说“方法不允许”。

If you want to try http commands, you need a web test tool such as PostMan .如果你想尝试 http 命令,你需要一个 web 测试工具,比如PostMan

In addition to the postman test method, another way to test the post request is to use ajax to send post request in jquery , here is a sample:除了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>

Here is the test result:这是测试结果: 在此处输入图片说明

I'm just going to add to this thread with my issue and resolution to same in case someone else stumbles upon this.我只是将我的问题和解决方案添加到此线程中,以防其他人偶然发现此问题。

I was receiving a 405 error code, despite the action being decorated with the HttpPost and ValidateAntiForgeryToken attributes, and ensuring the posted form data included the anti-forgery token.尽管使用 HttpPost 和 ValidateAntiForgeryToken 属性修饰了该操作,并确保发布的表单数据包含防伪令牌,但我还是收到了 405 错误代码。 Everything worked fine locally, but as soon as I put everything up on the server that's when I started receiving the 405 error.在本地一切正常,但是一旦我将所有内容都放在服务器上,我就开始收到 405 错误。 Turns out this error had nothing to do with what I had done in my app.原来这个错误与我在我的应用程序中所做的无关。 It was actually an issue in a stored procedure in my MySQL database.这实际上是我的 MySQL 数据库中存储过程中的一个问题。 Locally, case sensitivity isn't an issue, but on the server I had upper-cased the name of a table that was in lower-case, which caused an error to bubble up and give me this very obscure 405 error.在本地,区分大小写不是问题,但在服务器上,我将小写的表的名称大写,这导致错误冒泡并给我这个非常模糊的 405 错误。

I guess lesson learned here is to check EVERYTHING :)我想这里学到的教训是检查一切:)

Edit: For clarity, my issue relates to MySQL and Linux Hosting.编辑:为清楚起见,我的问题与 MySQL 和 Linux 托管有关。 Not sure if same would apply if using Windows hosting solutions如果使用 Windows 托管解决方案,不确定是否同样适用

Okay so I've been reading about removing the WebDav by entering in the web.config but that didn't work for me for core 3.1.好的,所以我一直在阅读有关通过输入 web.config 删除 WebDav 的信息,但这对我的核心 3.1 不起作用。 What you need to do is remove it from the IIS by:您需要做的是通过以下方式将其从 IIS 中删除:

  1. Expand the server in IIS 8在 IIS 8 中扩展服务器
  2. Select the site选择站点
  3. Click on handling mappings (For the site not server)单击处理映射(对于站点而不是服务器)
  4. Search for WebDav and remove it.搜索 WebDav 并将其删除。
  5. Restart IIS重启 IIS

Web.config should be left alone. Web.config 应该单独保留。 when i added the remove name=WebDav, my API stopped working.当我添加 remove name=WebDav 时,我的 API 停止工作。

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

note: you may need to also remove the one from the server if that doesn't work as I removed that first when I was troubleshooting.注意:如果这不起作用,您可能还需要从服务器中删除它,因为我在进行故障排除时首先删除了它。

Configure the CORS middleware properly.正确配置 CORS 中间件。 Add .AllowAnyMethod() after options.AllowAnyOrigin() as a chain.options.AllowAnyOrigin() .AllowAnyMethod()之后添加.AllowAnyMethod()作为链。 You may end up to this for testing purposes: app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());出于测试目的,您最终可能app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());

As another option, make sure that your web server (likely IIS) allows POST HTTP method besides GET .作为另一种选择,请确保您的 Web 服务器(可能是 IIS)除了GET之外还允许POST HTTP 方法。

Add [Route("MethodName")] in the header of the method in the controller.在控制器中方法的头部添加[Route("MethodName")] Just like:就像:

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

My solution was literally as stupid as adding a "/" to the end of my request URL.我的解决方案简直就像在我的请求 URL 的末尾添加“/”一样愚蠢。 Lost hours over it.浪费了几个小时。 GET worked fine without it.没有它,GET 工作得很好。

I am working on .Net 5 Api project, and came across this same issue.我正在研究.Net 5 Api项目,并遇到了同样的问题。 Adding lines below to the auto-generated web.config file when release is done:发布完成后,在自动生成的web.config文件中添加以下行:

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

to the <system.webServer> part of web.config andweb.config<system.webServer>部分和

  <handlers>
        <remove name="WebDAV" />
        <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
        <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,PUT,DELETE,DEBUG" type="System.Web.Handlers.TransferRequestHandler" resourceType="Unspecified" requireAccess="Script" preCondition="integratedMode,runtimeVersionv4.0" responseBufferLimit="0" />
        
        <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
  </handlers>

fixed it for me.为我修好了。 Some of the lines are probably a bit of an overkill, but I have philosophy "if it may not work in future, better to have it overengineered".有些行可能有点矫枉过正,但我的理念是“如果它将来可能不起作用,最好让它过度设计”。

However, I was struggling a lot with Azure DevOps CI-CD pipelines.但是,我在使用Azure DevOps CI-CD管道时遇到了很多困难。
I managed to do it, and wrote about how I did it here: Azure DevOps Release Pipeline Web.Config Edit我设法做到了,并在这里写了我是如何做到的: Azure DevOps Release Pipeline Web.Config

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM