c# – How to consume a webApi from asp.net Web API to store result in database?

















In this tutorial is explained how to consume a web api with C#, in this example a console application is used, but you can also use another web api to consume of course.

http://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-a-net-client

You should have a look at the HttpClient

HttpClient client = new HttpClient();
client.BaseAddress = new Uri(“http://localhost/yourwebapi”);

Make sure your requests ask for the response in JSON using the Accept header like this:

client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue(“application/json”));

Now comes the part that differs from the tutorial, make sure you have the same objects as the other WEB API, if not, then you have to map the objects to your own objects. ASP.NET will convert the JSON you receive to the object you want it to be.

HttpResponseMessage response = client.GetAsync(“api/yourcustomobjects”).Result;
if (response.IsSuccessStatusCode)
{
var yourcustomobjects = response.Content.ReadAsAsync<IEnumerable<YourCustomObject>>().Result;
foreach (var x in yourcustomobjects)
{
//Call your store method and pass in your own object
SaveCustomObjectToDB(x);
}
}
else
{
//Something has gone wrong, handle it here
}

please note that I use .Result for the case of the example. You should consider using the async await pattern here.









answered Oct 18 ’13 at 11:36






Nick N.Nick N.


9,77933 gold badges4141 silver badges6969 bronze badges


























For some unexplained reason this solution doesn’t work for me (maybe some incompatibility of types), so I came up with a solution for myself:

HttpResponseMessage response = await client.GetAsync(“api/yourcustomobjects”);
if (response.IsSuccessStatusCode)
{
var data = await response.Content.ReadAsStringAsync();
var product = JsonConvert.DeserializeObject<Product>(data);
}

This way my content is parsed into a JSON string and then I convert it to my object.








answered Nov 10 ’14 at 15:56






MalachiteBRMalachiteBR


50344 silver badges1010 bronze badges


























public class EmployeeApiController : ApiController
{
private readonly IEmployee _employeeRepositary;

public EmployeeApiController()
{
_employeeRepositary = new EmployeeRepositary();
}

public async Task<HttpResponseMessage> Create(EmployeeModel Employee)
{
var returnStatus = await _employeeRepositary.Create(Employee);
return Request.CreateResponse(HttpStatusCode.OK, returnStatus);
}
}

Persistance

public async Task<ResponseStatusViewModel> Create(EmployeeModel Employee)
{
var responseStatusViewModel = new ResponseStatusViewModel();
var connection = new SqlConnection(EmployeeConfig.EmployeeConnectionString);
var command = new SqlCommand(“usp_CreateEmployee”, connection);
command.CommandType = CommandType.StoredProcedure;
var pEmployeeName = new SqlParameter(“@EmployeeName”, SqlDbType.VarChar, 50);
pEmployeeName.Value = Employee.EmployeeName;
command.Parameters.Add(pEmployeeName);

try
{
await connection.OpenAsync();
await command.ExecuteNonQueryAsync();

command.Dispose();
connection.Dispose();

}
catch (Exception ex)
{

throw ex;
}
return responseStatusViewModel;
}

Repository

Task<ResponseStatusViewModel> Create(EmployeeModel Employee);

public class EmployeeConfig
{
public static string EmployeeConnectionString;
private const string EmployeeConnectionStringKey = “EmployeeConnectionString”;
public static void InitializeConfig()
{
EmployeeConnectionString = GetConnectionStringValue(EmployeeConnectionStringKey);
}

private static string GetConnectionStringValue(string connectionStringName)
{
return Convert.ToString(ConfigurationManager.ConnectionStrings[connectionStringName]);
}
}











B. Clay Shannon


24.3k112112 gold badges354354 silver badges696696 bronze badges








answered Sep 4 ’15 at 10:16






SrinivasSrinivas


12.2k11 gold badge1010 silver badges44 bronze badges





















Not the answer you’re looking for? Browse other questions tagged c# asp.net asp.net-web-api or ask your own question.



Source

Leave a comment

Your email address will not be published. Required fields are marked *