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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c#web api - 如何在post方法后返回ID?相关的知识,希望对你有一定的参考价值。

我有一个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;
        }
    }
答案

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

以上是关于c#web api - 如何在post方法后返回ID?的主要内容,如果未能解决你的问题,请参考以下文章