Reputation: 5862
I need to pass dataset
to web API to store dataset
in database. this is my c# client side code. Previously I pass person data like this (commented line). But in this time I have a Dataset
. How can I pass dataset
to web api using http POST?
DataSet rslt;
In this dataset
, there have four columns as pid,proid,name,msg
private void btnInsert_Click(object sender, EventArgs e)
{
using (var client = new HttpClient())
{
try
{
//person p = new person { PID = 1, ProjectID = 5, Name= "paul", Msg = "hello"};
client.BaseAddress = new Uri("http://localhost:10927/");
var response = client.PostAsJsonAsync("api/Person", p).Result;
if (response.IsSuccessStatusCode)
{
Console.Write("Success");
}
else
Console.Write("Error");
}
catch (Exception x)
{
Console.WriteLine(x.Message);
}
}
}
In my web API this part of my controller class:
public HttpResponseMessage Post([FromBody]Person value)
{
long id;
PersonPersistence dp = new PersonPersistence();
id = dp.addPerson(value);
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created);
response.Headers.Location = new Uri(Request.RequestUri, string.Format("Manager/{0}", id));
return response;
}
and this is part of my PersonPersistence.class
public long addPerson(Person t)
{
long id = 0;
try
{
string sqlString = "INSERT INTO tblperson(pid,proid,name,dis) VALUES (@1,@2,@3,@4);";
MySql.Data.MySqlClient.MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand(sqlString, conn);
cmd.Parameters.AddWithValue("@1", t.Time);
cmd.Parameters.AddWithValue("@2", t.Date);
cmd.Parameters.AddWithValue("@3", t.Batch);
cmd.Parameters.AddWithValue("@4", t.Leture);
cmd.ExecuteNonQuery();
id = cmd.LastInsertedId;
return id;
}
catch (MySqlException x)
{
Console.WriteLine(x.Number);
}
return id;
}
Upvotes: 0
Views: 3900
Reputation: 34421
You can convert datatable to an xml string using following
DataTable dt = new DataTable();
MemoryStream ms = new MemoryStream();
dt.WriteXml(ms);
long length = ms.Length;
ms.Position = 0;
byte[] buffer = new byte[length];
ms.Read(buffer,0,(int)length);
string xml = Encoding.UTF8.GetString(buffer);
Upvotes: 0