简体   繁体   中英

WebApi Post Methods always Returns “The requested resource does not support http method 'GET'.” Status: 405 Method Not Allowed

I Created a simple web api service to GET & POST User Data .

Every thing is well at Localhost. But when i host Service at server, Get Method is working fine when i call it from PostMan/Browser. But Post Methods always returns "The requested resource does not support http method 'GET'." Status: 405 Method Not Allowed .

One thing i got Confused here ie I requested a POST Call, but status message shows me 'GET' error. Why it should be? If it is CORS problem? I tried CORS enable too with various scenarios/aspects by searching answers on internet at Application level(Web.Config as well Nuget Package Manager Cors). Still getting 405 Method Not Allowed. Below pasted my API Code:

Controller NameSpaces:

  using MySql.Data.MySqlClient;
  using System;
  using System.Collections.Generic;
  using System.Data;
  using System.Linq;
  using System.Net;
  using System.Net.Http;
  using System.Web.Http;
  using System.Web.Http.Cors;

Controller

  public class UsersController : ApiController
  {
    [Route("api/Users/GetUsers/{UserId}")]
    [HttpGet]
    public IEnumerable<User> GetUsers(int UserId)
    {
        try
        {
            List<User> userlist = new List<User>();
            MySqlCommand cmd = new MySqlCommand("GetUsers");
            cmd.Parameters.AddWithValue("aUserId", UserId);
            cmd.CommandType = CommandType.StoredProcedure;
            DataTable dt = obj.GetData(out ErrorMsg, cmd);
            // Did Some Stuff and Returns Model;
            return userlist;
        }
        catch(Exception ex)
        {
            // Written Error Log & Returns Empty Model;
        }
    }

    [Route("api/Users/SaveUser")]
    [HttpPost]
    public IEnumerable<User> SaveUser([FromBody]dynamic request)
    {
        try
        {
            string UserName = request.Param_Name;
            string Email = request.Param_Email;
            List<User> userlist = new List<User>();
            MySqlCommand cmd = new MySqlCommand("UserSave");
            cmd.Parameters.AddWithValue("aUserName", UserName);
            cmd.Parameters.AddWithValue("aEmail", Email);
            cmd.CommandType = CommandType.StoredProcedure;
            DataTable dt = obj.GetData(out ErrorMsg, cmd);
            UserAuthenticate userdata;
            // Did Some Stuff and returns UserModel;
            return userlist;
        }
        catch(Exception Ex)
        {
            // Written Error Log & Returns Empty Model with Error Message;
        }
    }

    [Route("api/Users/SaveUserModel")]
    [HttpPost]
    public IEnumerable<User> SaveUserModel([FromBody]User request)
    {
        try
        {
            string Param_UserName = request._UserName;
            string Param_Email = request._Email;
            List<User> userlist = new List<User>();
            MySqlCommand cmd = new MySqlCommand("UserSave");
            cmd.Parameters.AddWithValue("aUserName", Param_UserName);
            cmd.Parameters.AddWithValue("aEmail", Param_Email );
            cmd.CommandType = CommandType.StoredProcedure;
            DataTable dt = obj.GetData(out ErrorMsg, cmd);
            UserAuthenticate userdata;
            // Did Some Stuff and returns UserModel;
            return userlist;
        }
        catch(Exception Ex)
        {
            // Written Error Log & Returns Empty Model with Error Message;
        }
    }
 }

Model

public class User
{
    public int _UserID { get; set; }
    public string _Email { get; set; }
    public string _UserName { get; set; }
}

Web.Config

Web.Config File Pasted here in Image

WebApi.Config

Namespaces

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

WebApiConfig Class

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
        var cors = new EnableCorsAttribute("*", "*", "*");
        config.EnableCors(cors);
        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
        config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
    }
}

PostMan Request & Response

Headers for Above PostMan Request

Access-Control-Allow-Methods →*
Access-Control-Allow-Origin →*
Access-Control-Request-Headers →: *
Access-Control-Request-Method →: *
Allow →POST
Cache-Control →no-cache
Content-Length →72
Content-Type →application/json; charset=utf-8
Date →Wed, 16 Nov 2016 17:50:03 GMT
Expires →-1
Pragma →no-cache
Server →Microsoft-IIS/7.5
X-AspNet-Version →4.0.30319

Thanks for any Helps!! Got Wasted a Day for this error.

I know this is an old post but, for anyone else looking for a solution to this problem. I had this issue and realized that I was posting to my webapi using http but IIS was redirecting my request to https. This redirect was causing postman to change the POST to a GET. changing my URL to https fixed the problem for me.

here is the solution of your problem

ASP.NET WebApi : (405) Method Not Allowed

Finally I changed the cookieless="AutoDetect" in web.config to cookieless="UseCookies" and the problem solved.

If you have not Enabled CORS decorate your controller as below.

  [EnableCors(origins: "*", headers: "*", methods: "GET, POST, PUT, DELETE")] 

Also put belo code in webapiconfig.cs file

  config.EnableCors();

If you are hosting your endpoints in public api then decorate controller as below.

 [RoutePrefix("api/users")]
    public class usersController : ApiController

Then Get for example,

   //Get http:192.168.0.0:2210/api/users/
      [Route("~/api/users")]

     //POST  http:192.168.0.0:2210/api/users/
     [Route("~/api/users")] 

    //Get on id
     //POST  http:192.168.0.0:2210/api/users/
     [Route("~/api/users/{id}")] 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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