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

c# web api - How to return ID after post method?

我有一个 post 方法可以将客户添加到数据库中。但是在 post 完成后,我在 postman 中得到的 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;
        }
    }

您需要使用 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;
        }
    }