简体   繁体   English

ASP.NET Web API:“消息”:“请求的资源不支持 http 方法 'POST'、PUT、DELETE。” 在邮递员

[英]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.我正在尝试创建一个简单的ASP.NET Web API ,它将条目(pharmacyName, pharmacyAddress, pharmacyCategory)获取、发布、放置和删除到MySQL数据库中。 Both my "GET" functions successfully execute, but when I test POST, PUT , or DELETE functionality in Postman , I receive the following error:我的两个"GET"函数都成功执行,但是当我在Postman测试POST, PUTDELETE功能时,我收到以下错误:

"Message": "The requested resource does not support http method 'POST'." "Message": "请求的资源不支持 http 方法 '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:我在 Postman 中使用的请求 URL 是"localhost:59353/api/values/ 。下面是我的ValuesController.cs, RouteConfig.cs, and WebAPIConfig.cs文件中的代码块:

ValuesController.cs POST method: ValuesController.cs POST 方法:

// 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: 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: 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.string、int、float等简单类型将从 .Net 框架中的查询字符串中获取,而复杂类型总是从 body 中获取。

Solution-1解决方案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.在这种情况下,.Net Framework 需要来自查询参数的字符串pharmacyAddresspharmacyCategory ,您可以像这样调用 API,而无需对服务器端代码进行任何更改。

Note:Also you don't need to define key of the parameter (in http request) which is being defined as [From Body] .注意:您也不需要定义被定义为[From Body]的参数的键(在 http 请求中)。 As total of one simple type can be passed using [FromBody] attribute which you can see below like this =pharmacyNameContent因为总共可以使用[FromBody]属性传递一种简单类型,您可以在下面看到这样的=pharmacyNameContent

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

Solution-2解决方案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或者您可以通过将所有参数放在复杂模型中来调用您的 API,并通过主体而不是像这样的查询参数传递参数

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现在你可以像这样通过 body 传递参数来使用你的 API

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它肯定会工作,因为它已经从我的角度实施和测试

暂无
暂无

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

相关问题 ASP.NET Web Api“请求的资源不支持http方法PUT / DELETE” - ASP.NET Web Api “The requested resource does not support http method PUT/DELETE” “请求的资源不支持HTTP方法&#39;PUT&#39;ASP.Net Web API - "The requested resource does not support HTTP method 'PUT' ASP.Net Web API Asp.net Web api请求的资源不支持http方法&#39;GET&#39; - Asp.net Web api The requested resource does not support http method 'GET' ASP.NET Web API - 请求的资源不支持 Z80791B3AE7002CB88C246876D9FA 方法 - ASP.NET Web API - The requested resource does not support http method 'GET' Web API - 405 - 请求的资源不支持http方法&#39;PUT&#39; - Web API - 405 - The requested resource does not support http method 'PUT' WEB API错误404-“消息”:“请求的资源不支持http方法&#39;PUT&#39;。” - WEB API error-404 - “Message”: “The requested resource does not support http method 'PUT'.” MVC和Web Api:请求的资源不支持http方法“ POST” - MVC and Web Api: The requested resource does not support http method 'POST' ASP.Net-请求的资源不支持http方法“ GET” - ASP.Net - Requested resource does not support http method 'GET' “消息”:“请求的资源不支持http方法&#39;POST&#39;。” .net api中的JSON返回 - “Message”: “The requested resource does not support http method 'POST'.” JSON return in .net api “消息”:“请求的资源不支持http方法&#39;PUT&#39;。” - “Message”: “The requested resource does not support http method 'PUT'.”
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM