Using async with C# web api post method

  • Thread starter Thread starter CSharp Enthusiast
  • Start date Start date
C

CSharp Enthusiast

Guest
Hi, I am working on a POST() method to be run asynchronously. The below code runs fine in a sequential manner.

public class DataController : Controller
{
private IList<string> errors = new List<string>();

[HttpPost]
[Route("data/import", Name = "DataImport")]
public IActionResult Post()
{
var rawdata = ConvertToByteArray(Request.Body);
var rdrec = Encoding.UTF8.GetString(content).Split(new string[] { Environment.NewLine, @"\r" }, StringSplitOptions.None).ToList();

Task.Run(() => importdata(rdrec)); //Trying to run asynchronously

if (errors.Count == 0)
return Ok("POST");
else
return Ok(errors);
}

private void importdata(IList<string> lines)
{
//string connectionString = @"Data Source=localhost;Initial Catalog=TEST_DB;Integrated Security=True";
string connectionString = ConfigurationManager.ConnectionStrings["SQLDBCONN"].ConnectionString; // Added this to appsettings.json file and get null reference error in ASP.net core; works fine in ASP.net web api
var message = "";

var Data = from line in lines
let data = line.Split(',')
select new filedata
{
ID = data[0],
Type = data[1],
Status = data[2],
Description = data[3]
};

using (SqlConnection sqldbConnection = new SqlConnection(connectionString))
{
sqldbConnection.Open();
foreach (var i in Data)
{
try
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO [dbo].[testImport] ([ID], [Type], [Status], [Description]) VALUES (@ID, @Type, @Status, @Description)", sqldbConnection))
{
cmd.Parameters.AddWithValue("@ID", i.ID);
cmd.Parameters.AddWithValue("@Type", i.Type);
cmd.Parameters.AddWithValue("@Status", i.Status);
cmd.Parameters.AddWithValue("@Description", i.Description);
cmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
message = ex.StackTrace;
return (message);
}
}

}

}

private byte[] ConvertToByteArray(Stream stream)
{
using (MemoryStream ms = new MemoryStream())
{
stream.CopyTo(ms);
return ms.ToArray();
}
}
}

Could you please guide me on how to re-write the POST method and SqlBulkCopy run asynchronously.

Thank you in advance.


SQLEnthusiast

Continue reading...
 
Back
Top