Axl Rose Villanueva
Axl Rose Villanueva

Reputation: 61

Asp.Net Core 3.1 405 Method Not Allowed

Hi Guys I need help.. I always get 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

Here is the My 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

    // 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

Upvotes: 6

Views: 40172

Answers (8)

Kadaj
Kadaj

Reputation: 695

I am working on .Net 5 Api project, and came across this same issue. Adding lines below to the auto-generated web.config file when release is done:

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

to the <system.webServer> part of web.config and

  <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.
I managed to do it, and wrote about how I did it here: Azure DevOps Release Pipeline Web.Config Edit

Upvotes: 2

flashsplat
flashsplat

Reputation: 537

My solution was literally as stupid as adding a "/" to the end of my request URL. Lost hours over it. GET worked fine without it.

Upvotes: 1

Junaid Pathan
Junaid Pathan

Reputation: 4306

Add [Route("MethodName")] in the header of the method in the controller. Just like:

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

Upvotes: 0

crucifery
crucifery

Reputation: 458

Configure the CORS middleware properly. Add .AllowAnyMethod() after options.AllowAnyOrigin() as a chain. You may end up to this for testing purposes: app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());

As another option, make sure that your web server (likely IIS) allows POST HTTP method besides GET.

Upvotes: 1

mbuchok
mbuchok

Reputation: 409

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. Everything worked fine locally, but as soon as I put everything up on the server that's when I started receiving the 405 error. 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. 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.

I guess lesson learned here is to check EVERYTHING :)

Edit: For clarity, my issue relates to MySQL and Linux Hosting. Not sure if same would apply if using Windows hosting solutions

Upvotes: 1

Xavier
Xavier

Reputation: 107

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. What you need to do is remove it from the IIS by:

  1. Expand the server in IIS 8
  2. Select the site
  3. Click on handling mappings (For the site not server)
  4. Search for WebDav and remove it.
  5. Restart IIS

Web.config should be left alone. when i added the remove name=WebDav, my API stopped working.

  <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.

Upvotes: 0

LouraQ
LouraQ

Reputation: 6881

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:

        <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: enter image description here

Upvotes: 1

Art Tsai
Art Tsai

Reputation: 139

Looking at the provided image, you use chrome to issue the url request, which is a HTTP GET command. So, your app got an HTTP GET command but your method wants to accept an HTTP POST method. That's why it says 'method not allowed'.

If you want to try http commands, you need a web test tool such as PostMan.

Upvotes: 6

Related Questions