简体   繁体   中英

ASP.NET Web API: "Message": "The requested resource does not support http method 'POST', PUT, DELETE." in Postman

I am trying to create a simple ASP.NET Web API that gets, posts, puts, and deletes entries (pharmacyName, pharmacyAddress, pharmacyCategory) into a MySQL database. Both my "GET" functions successfully execute, but when I test POST, PUT , or DELETE functionality in Postman , I receive the following error:

"Message": "The requested resource does not support http method 'POST'."

I have searched the forums and the Web for a solution, but I have been unable to find an answer pertaining to my case. I am a beginner, so please forgive me if I overlooked something or used improper/confusing terminology or coding structure.

The request URL I am using in Postman is "localhost:59353/api/values/ . Below are blocks of code from my ValuesController.cs, RouteConfig.cs, and WebAPIConfig.cs files:

ValuesController.cs POST method:

// POST api/values
[System.Web.Http.HttpPost]
public void Post([FromBody]string pharmacyName, string pharmacyAddress, string pharmacyCategory)
{

    MySqlConnection conn = WebApiConfig.conn();

    MySqlCommand query = conn.CreateCommand();

    query.CommandText = "INSERT INTO locations (pharmacyName, pharmacyAddress, pharmacyCategory) VALUES (@pharmacyName, @pharmacyAddress, @pharmacyCategory)";

    query.Parameters.AddWithValue("@pharmacyName", pharmacyName);
    query.Parameters.AddWithValue("@pharmacyAddress", pharmacyAddress);
    query.Parameters.AddWithValue("@pharmacyCategory", pharmacyCategory);


    var results = new List<results>();

    try
    {
        conn.Open();
    }

    catch (MySql.Data.MySqlClient.MySqlException ex)
    {
        results.Add(new results(null, null, null, ex.ToString()));
    }

    MySqlDataReader fetch_query = query.ExecuteReader();

    while (fetch_query.Read())
    {
        results.Add(new results(fetch_query["pharmacyName"].ToString(), fetch_query["pharmacyAddress"].ToString(), fetch_query["pharmacyCategory"].ToString(), null));
    }


}

RouteConfig.cs:

public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }
    }

WebAPIConfig.cs:

public static class WebApiConfig
    {
        public static MySqlConnection conn()
        {
            string conn_string = "server=localhost;port=3306;database=map;username=root;password=123456";

            MySqlConnection conn = new MySqlConnection(conn_string);

            return conn;
        }
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

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

Simple types like string,int,float etc are to be fetched from query string in .Net framework where as complex types always fetched from body.

Solution-1

In this case .Net Framework is expecting string pharmacyAddress and pharmacyCategory from query parameters and you can call your API like this without making any change to your server side code.

Note:Also you don't need to define key of the parameter (in http request) which is being defined as [From Body] . As total of one simple type can be passed using [FromBody] attribute which you can see below like this =pharmacyNameContent

POST /api/values?pharmacyAddress=myaddress&pharmacyCategory=mycategory HTTP/1.1
Host: localhost:59353
Content-Type: application/x-www-form-urlencoded
=pharmacyNameContent

Solution-2

Or you can call your API by putting all your params in complex model and pass params through body instead of query parameters like this

Complex Type Model

public class PharmacyModel
    {
        public string PharmacyName { get; set; }
        public string PharmacyAddress { get; set; }
        public string PharmacyCategory { get; set; }
    }

API code

[System.Web.Http.HttpPost]
public void Post(PharmacyModel pharamcyModel)
{
    MySqlConnection conn = WebApiConfig.conn();
    MySqlCommand query = conn.CreateCommand();

    //Access your propeties like this
    query.CommandText = "INSERT INTO locations (pharamcyModel.PharmacyName, pharamcyModel.PharmacyAddress, pharamcyModel.PharmacyCategory) VALUES (@pharmacyName, @pharmacyAddress, @pharmacyCategory)";

  //rest of the coding
}

And now you can consume your API by passing paramters through body like this

POST /api/values? HTTP/1.1
Host: localhost:59353
Content-Type: application/x-www-form-urlencoded

pharmacyAddress=myaddress&pharmacyCategory=mycategory&pharmacyName=nameOfPharmacy

It will surely gonna work as its already implemented and tested from my end

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