c#web api - 如何在post方法后返回ID?

时间:2018-03-03 12:05:06

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

我有一个post方法,可以将客户添加到数据库中。但是在帖子结束后,我在CustomerID的邮递员中获得的结果总是为0。 其他两个参数工作正常(名称和地址),当我检查数据库时,id字段插入应该是。 这是我从控制器发布的post方法。

 [HttpPost]
    [ActionName("postCustomerBy")]
    public HttpResponseMessage Post([FromBody]Customer customer)
    {
        customer = rep.Add(customer);
        var response = Request.CreateResponse(HttpStatusCode.Created, customer);
        string uri = Url.Link("DefaultApi", new { id = customer.CustomerID });
        response.Headers.Location = new Uri(uri);
        return response;
    }

编辑:这是我添加客户的功能:

 public Customer Add(Customer customer)
    {
        string query = "INSERT INTO Customer(Name,Address) VALUES (@Name,@Address)";
        using (SqlConnection con = new SqlConnection(conString))
        {
            using (SqlCommand cmd = new SqlCommand(query, con))
            {
                cmd.Parameters.AddWithValue("@Name", customer.Name);
                cmd.Parameters.AddWithValue("@Address", customer.Address);
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
            }
            return customer;
        }
    }

1 个答案:

答案 0 :(得分:3)

您需要使用OUTPUT INSERTED.ID并将返回的值影响到customer.CustomerID,如下所示:

public Customer Add(Customer customer)
    {
        string query = "INSERT INTO Customer(Name,Address) OUTPUT INSERTED.ID VALUES (@Name,@Address)";
        using (SqlConnection con = new SqlConnection(conString))
        {
            using (SqlCommand cmd = new SqlCommand(query, con))
            {
                cmd.Parameters.AddWithValue("@Name", customer.Name);
                cmd.Parameters.AddWithValue("@Address", customer.Address);
                con.Open();
                customer.CustomerID = (int)cmd.ExecuteScalar();
                con.Close();
            }
            return customer;
        }
    }