如果我在呼叫中使用相同的URL,我的控制器如何知道何时执行一种方法而不是另一种方法(更新/插入)?

时间:2013-09-11 17:36:59

标签: c# asp.net-web-api

插入:

[HttpPost]
public void InsertDirector(Director director)
{
    myConnection.Open();
    var query = "INSERT INTO dbo.AWD_Directors (AwardTitleId, PersonId, NameId,  DirectorSequence, IsOnBallot, Concatenation, WhoEntered, WhoChanged) VALUES (" + director.AwardTitleId + ", " + director.PersonId + ", " + director.NameId + ", " + director.DirectorSequence + ", " + director.IsOnBallot + ", '" + director.Concatenation + "', 0, 0)";
    var cmd = new SqlCommand(query, myConnection);
    cmd.ExecuteNonQuery();
    myConnection.Close();
}

更新:

[HttpPost]
public void UpdateDirector(Director director)
{
  myConnection.Open();
  var query = "UPDATE dbo.AWD_Directors SET NameId=" + director.NameId + ", DirectorSequence = " + director.DirectorSequence + ", IsOnBallot = " + director.IsOnBallot + ", Concatenation = '" + director.Concatenation + "' WHERE AwardTitleId = " + director.AwardTitleId + "AND PersonId = " + director.PersonId + " AND NameId = " + director.NameId;
  var cmd = new SqlCommand(query, myConnection);
  cmd.ExecuteNonQuery();
  myConnection.Close();
}

插入路线:

routes.MapHttpRoute(name: "InsertDirector", routeTemplate: "api/awards/directors", defaults: new
{
    controller = "Awards", action = "InsertDirector"
});

更新路线:

routes.MapHttpRoute(name: "UpdateDirector", routeTemplate: "api/awards/directors", defaults: new
{
    controller = "Awards",
    action = "UpdateDirector"
 });

我可以使用哪些命名约定来改进我的内容?

顺便说一下,不要介意内联SQL。这将在稍后更改。

2 个答案:

答案 0 :(得分:1)

REST的惯例是我们使用HttpMethods进行CRUD操作选择:

  • GET - 读取操作(列表和GetById)
  • POST - 插入
  • PUT - Udpating
  • 删除 - 删除

详细说明:Creating a Web API that Supports CRUD Operations

然后使用非常默认的路由设置(请参阅此处:Routing in ASP.NET Web API

routes.MapHttpRoute(
    name: "API Default",
    routeTemplate: "api/{controller}/{id}",   // the Director as controller
    defaults: new { id = RouteParameter.Optional }
);

所以,我们刚刚指示了Web API基础架构,如果有方法:

[HttpPost]
public void InsertDirector(Director director) ...

它将用于创建,并且使用的HttpMethod必须是POST

//[HttpPost]
[HttpPut]      // !! Attention, here is the difference
public void UpdateDirector(Director director)... 

如果HttpMethod为UpdateDirector,则会调用PUT

注意:因为在更新期间我们确实拥有现有产品的ID,因此Update方法应如下所示:

// the id parameter is a convention as well, 
// to be sure that we are updating existing item
// so this would be better
public void UpdateDirector(int id, Director director)... 

答案 1 :(得分:0)

如果是插入/更新的情况,我假设您在某处有一个ID字段(隐藏的HTML)。您应该调用相同的方法,该方法将具有以下逻辑

如果ID为null或ZERO。做插件
如果ID是正数。进行ID = html.ID

的更新