如何使用asp.net Web API中的webApi将结果存储到数据库中?

时间:2013-10-18 11:33:47

标签: c# asp.net asp.net-web-api

我想知道如何从另一个ASP.Net Web API使用WEBAPI来将响应存储在数据库中。 我知道如何从javascript,控制台应用程序等客户端使用WEBAPI。

但要求是通过我的WEBAPI& amp;提取第三方API的数据。将结果存储在数据库中,以便使用我的WEBAPI,我的客户请求我提供数据。

是否可以使用Asp.Net Web API执行此操作?

3 个答案:

答案 0 :(得分:91)

在本教程中解释了如何使用C#使用 web api ,在此示例中使用了控制台应用程序,但您也可以使用其他 web api 来使用当然。

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

您应该查看HttpClient

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

确保您的请求使用Accept标头在JSON中请求响应:

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

现在出现与教程不同的部分,确保您拥有与其他WEB API相同的对象,否则,您必须将对象映射到您自己的对象。 ASP.NET会将您收到的JSON转换为您想要的对象。

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
}

请注意我使用.Result作为示例的情况。您应该考虑在此使用async await模式。

答案 1 :(得分:9)

由于某些无法解释的原因,这个解决方案对我不起作用(可能是某些类型不兼容),所以我为自己想出了一个解决方案:

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

这样我的内容被解析为JSON字符串,然后我将其转换为我的对象。

答案 2 :(得分:1)

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);
    }
} 

持久性

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;
            }

存储库

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]);
    }
}