POST method for RESTful API
本文关键字:API RESTful for method POST | 更新日期: 2023-09-27 17:58:06
我还是.NET、C#、RESTful API的初学者。现在,我正在学习RESTful API中的POST方法。这是POST方法的示例编码,但我仍然无法理解编码的含义。有人能以一种清晰易懂的方式为我解释每一行代码吗?或者,如果你不介意,你能用评论的方式向我解释一下吗?例如:
public string message; //to declare message for what use...`
public class MessageController : ApiController
{
// GET api/values
public class MessageToShow
{
public string message;
public string from;
}
public List<MessageToShow> Get()
{
var x = new cheeAdDCClf3rfFREntities();
var y=x.messages.Take(100);
List<MessageToShow> messageToShow = new List<MessageToShow>();
foreach (var xx in y)
{
MessageToShow m = new MessageToShow();
member me = x.members.FirstOrDefault(j => j.ID == xx.from);
if (me != null)
{
m.from = me.username;
m.message = xx.message1;
messageToShow.Add(m);
}
}
return messageToShow;
}
// POST api/values
public void Post(int memberid, dynamic value)
{
var x = new cheeAdDCClf3rfFREntities();
message m = new message();
m.ID = x.messages.Max(record => record.ID) + 1;
m.from = memberid;
m.message1 = value.value;
x.messages.Add(m);
x.SaveChanges();
}
}
}
如果有人愿意和我分享你的编程知识,我将不胜感激。非常感谢!!^_^
看起来您发布了GET
和POST
方法的代码。
当我对您的API进行GET
时:
public List<MessageToShow> Get()
{
// Looks like EntityFramework? Represents the items already in database
var x = new cheeAdDCClf3rfFREntities();
// Take to top 100 item already in the database
var y=x.messages.Take(100);
// Create a new list to hold the messages we will return
List<MessageToShow> messageToShow = new List<MessageToShow>();
// For each message in the 100 we just took
foreach (var xx in y)
{
MessageToShow m = new MessageToShow();
// Get the details of the member that send this message
member me = x.members.FirstOrDefault(j => j.ID == xx.from);
// If we found the member, create a message to show
// (populating the message and the username of the member
// who sent it)
if (me != null)
{
m.from = me.username;
m.message = xx.message1;
messageToShow.Add(m);
}
}
// Return the list of messages we just created to the caller of the API
return messageToShow;
}
当我POST
到您的API时,会发生以下情况:
public void Post(int memberid, dynamic value)
{
// Gets the items already in the database
var x = new cheeAdDCClf3rfFREntities();
// Create a new message object
message m = new message();
// Find the highest ID already in the database, then add 1. This is the
// ID for our new item
m.ID = x.messages.Max(record => record.ID) + 1;
// The 'from' property is set to the memberId that the user passed in the POST
m.from = memberid;
// The 'message' property is set to whatever dynamic value is passed in the POST
m.message1 = value.value;
// Add the message to the database
x.messages.Add(m);
x.SaveChanges();
}
要了解更多关于REST的信息,您可以阅读以下内容:
HTTP和REST 初学者指南
您发布的代码实际上看起来更像EntityFramework,这是一种与数据库交互的方式。它不是特定于API的。
您可以在这里找到更多关于EF的信息:
EntityFramework