简体   繁体   English

GET,POST,PUT哪个应用于将json对象接收到我的rest api并作为响应发送json对象?

[英]GET,POST,PUT Which should be used for receiving a json object to my rest api and send a json object in response?

I'm writing my first web API using MVC. 我正在使用MVC编写我的第一个Web API。

I'm aware that POST and PUT are usually implemented to define the HTTP methods for inserting or updating a database behind an API. 我知道,通常执行POST和PUT来定义用于在API后面插入或更新数据库的HTTP方法。 But all I want to do is receive a JSON object from the caller, do some processing then return another JSON object in response. 但是我要做的就是从调用方接收一个JSON对象,进行一些处理,然后返回另一个JSON对象作为响应。 No database is involved. 不涉及数据库。

I've tested using both POST and GET in my API controller method and they both work ok but which http method should I actually be using for best practice? 我已经在API控制器方法中同时使用POST和GET进行了测试,它们都可以正常工作,但实际上我应该使用哪种http方法以获得最佳实践?

eg 例如

public IHttpActionResult Get(ApiEquipment equipment)
{
    // Convert equipment to a compatible buffer
    return Ok(new ConvertToBuffer(equipment));
}

GET is useful for SAFE(*) operations where you do not need to pass many parameters to the server - all of the parameters must be in the URL as GET operations do not pass data in the HTTP body. GET对于不需要向服务器传递许多参数的SAFE(*)操作很有用-所有参数都必须在URL中,因为GET操作不会在HTTP正文中传递数据。

POST is useful for UNSAFE(*) operations or operations where you need to pass large amounts of data to the server as the data can be passed in the HTTP body. POST对于UNSAFE(*)操作或需要将大量数据传递到服务器的操作很有用,因为可以在HTTP正文中传递数据。

Use GET for simple queries and calculations with few parameters. 使用GET进行参数较少的简单查询和计算。 Use POST for large payloads or operations that change server state (such as updating something or performing complex bussiness operations). 对于大型有效负载或更改服务器状态的操作(例如,更新某些内容或执行复杂的业务操作),请使用POST。

See the HTTP method definitions in RFC 7231 for more in-depth information. 有关更多详细信息,请参阅RFC 7231中HTTP方法定义

(*) SAFE operations are operations that do not change (visible) server state. (*)SAFE操作是不会更改(可见)服务器状态的操作。 UNSAFE operations do change (visible) server state. UNSAFE操作确实会更改(可见)服务器状态。

GET

It seems that your just want to retrieve data in a meaningful representation (response after processing) from the raw data (request from the caller). 似乎您只想从原始数据(调用方的请求)中以有意义的表示形式(处理后响应)检索数据。 There is no modification / insertion of data, so GET should be use. 没有修改/插入数据,因此应该使用GET

The POST verb seems to be what you want. POST动词似乎就是您想要的。

If I understand correctly, you want to send a JSON from the client to server. 如果我理解正确,则希望将JSON从客户端发送到服务器。 Then the server will modify the JSON and return it to the client. 然后,服务器将修改JSON并将其返回给客户端。

In REST APIs, POST is commonly used to create a new resource . 在REST API中, POST通常用于创建新资源 But it's also a catch-all verb for operations that should not be executed using the other methods. 但这也是不应该使用其他方法执行的操作的笼统动词

For more details on using POST to invoke arbitrary processing, have a look at this answer . 有关使用POST调用任意处理的更多详细信息,请查看此答案

I would suggest you to use 'HTTPPOST' if you require to process your JSON object else use GET method. 如果需要处理JSON对象,我建议您使用“ HTTPPOST”,否则请使用GET方法。

Consider this example for using HttpPost method since I process the JSON object to get some info from database. 考虑一下使用HttpPost方法的示例,因为我处理了JSON对象以从数据库中获取一些信息。

    [HttpPost]
    public IHttpActionResult Masters([FromBody]Download_Config_UserInfo Info)
    {
        List<TestMaster> testMaster = null;
        ResponseValidation objValidation = new ResponseValidation();
        try
        {
            #region Validation
            objValidation = base.ValidateRequest(Info);
            if (!objValidation.isValid)
                return base.JsonErrorResult(this.MasterName, objValidation.ErrorCode, objValidation.ErrorDesc);
            #endregion

            #region Initialization
            this.Initialization();
            #endregion

            #region Functionality

            //testMaster = this.GetTestMaster();
            testMaster = this.GetTestDateMaster();                
            if (testMaster == null)
                return base.JsonErrorResult(this.MasterName, "E19", "Data Not Available");

            var result = (from a in testMaster
                          select new object[]
                          {
                              a.TestId,
                              a.TestName
                          });
            #endregion

            return base.JsonResult(this.MasterName, this.Fields, result);

        }
        catch (Exception ex)
        {
            loggerService.Error(Info.ToJSON(), this.MasterName, ex);
            return base.JsonErrorResult(this.MasterName, "E20", "Internal Server Error", ex.Message + "_" + ex.StackTrace);
        }
        finally
        {
            testMaster = null; objValidation = null; base.UserMaster = null; base.UserPositionMapping = null;
        }
    }

    #endregion

    #region Functionality

    [NonAction]
    public List<TestMaster> GetTestMaster()
    {
        List<ADM_Retailer> testMaster = null;
        try
        {
            testMaster = this.GetTest();
            if (testMaster == null || (testMaster.Count == 0)) { return null; }

            string weekNo = base.GetWeekNumber();

            return (from a in testMaster
                    select new TestMaster
                    {
                        TestId = a.ARTR_Id,
                        TestName = a.ARTR_Name,
                    }).ToList();
        }
        finally { }
    }

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

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