【发布时间】:2021-10-31 21:15:45
【问题描述】:
我写了一个控制器。我根据我将在此处使用的 web api 编写它。但是我应该如何制作自己创建的 api?
我是否需要在使用HttpPost 编写的地方创建自己的api?我可能是错的,因为我是新手。
public class GoldPriceDetailController : Controller
{
string Baseurl = "https://apigw.bank.com.tr:8003/";
public async Task<ActionResult> GetGoldPrice()
{
List<GoldPrice> goldPriceList = new List<GoldPrice>();
using (var client = new HttpClient())
{
//Passing service base url
client.BaseAddress = new Uri(Baseurl);
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//Sending request to find web api REST service resource GetDepartments using HttpClient
HttpResponseMessage Res = await client.GetAsync("getGoldPrices");
Console.WriteLine(Res.Content);
//Checking the response is successful or not which is sent using HttpClient
if (Res.IsSuccessStatusCode)
{
var ObjResponse = Res.Content.ReadAsStringAsync().Result;
goldPriceList = JsonConvert.DeserializeObject<List<GoldPrice>>(ObjResponse);
}
//returning the student list to view
return View(goldPriceList);
}
}
[HttpPost]
public async Task<IActionResult> GetReservation(int id)
{
GoldPrice reservation = new GoldPrice();
using (var httpClient = new HttpClient())
{
using (var response = await httpClient.GetAsync("https://apigw.bank.com.tr:8443/getGoldPrices" + id))
{
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
string apiResponse = await response.Content.ReadAsStringAsync();
reservation = JsonConvert.DeserializeObject<GoldPrice>(apiResponse);
}
else
ViewBag.StatusCode = response.StatusCode;
}
}
return View(reservation);
}
}
【问题讨论】:
-
这不是您问题的答案,但我建议read more about using
HttpClient。对于这个问题,你能提供更多细节吗?你想要达到的目标还不够清楚。 -
我想使用我创建的 API 从外部 Web API 中提取数据。我不知道从哪里开始。
标签: asp.net-core asp.net-core-mvc asp.net-core-webapi