C# 如何从asp.net Web API 使用webApi 将结果存储在数据库中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19448690/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to consume a webApi from asp.net Web API to store result in database?
提问by Karthik Dheeraj
I'm wondering how to consume a WEBAPI from another ASP.Net Web API to store the response in a database. I know how to consume a WEBAPI from clients like javascript,console application etc.
我想知道如何使用来自另一个 ASP.Net Web API 的 WEBAPI 将响应存储在数据库中。我知道如何从 javascript、控制台应用程序等客户端使用 WEBAPI。
But the requirement is to pull the data from third party API by my WEBAPI & store the result in a database so that using my WEBAPI my clients request me for data.
但要求是通过我的 WEBAPI 从第三方 API 提取数据并将结果存储在数据库中,以便使用我的 WEBAPI 我的客户请求我提供数据。
Is it possible to do this with an Asp.Net Web API?
是否可以使用 Asp.Net Web API 来做到这一点?
采纳答案by Nick N.
In this tutorial is explained how to consume a web apiwith C#, in this example a console application is used, but you can also use another web apito consume of course.
在本教程中解释了如何使用 C#使用web api,在本示例中使用的是控制台应用程序,但您当然也可以使用其他web api来使用。
http://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-a-net-client
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
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:
确保您的请求使用 Accept 标头以 JSON 格式请求响应,如下所示:
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.
现在是与教程不同的部分,请确保您具有与另一个相同的对象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
}
please note that I use .Result
for the case of the example. You should consider using the async
await
pattern here.
请注意,我.Result
用于示例的情况。您应该考虑在async
await
此处使用该模式。
回答by MalachiteBR
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.
通过这种方式,我的内容被解析为 JSON 字符串,然后我将其转换为我的对象。
回答by Srinivas
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]);
}
}