Emi*_*las 2 c# api asp.net-core-mvc asp.net-core
我想对各种服务进行 HTTP 调用,POST/GET/DELETE..,并读取响应 JSON 和 XML,如何在服务器端的 C# 中执行此操作?
简而言之:如何从 Asp.Net Core C# 进行 Api 调用。
客户端 Ajax 不起作用,(对于跨域)
试试这个代码:To make Api call from Asp.Net Core, Server Side (C#).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace core.api.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
[HttpGet]
public async Task<ActionResult<string>> Get()
{
string url="https://jsonplaceholder.typicode.com/todos"; // sample url
using (HttpClient client = new HttpClient())
{
return await client.GetStringAsync(url);
}
}
}
Run Code Online (Sandbox Code Playgroud)
}
使用ajax调用控制器:
$.ajax({
type: "GET",
url: "/API/Gumtreetoken?user=username&pasword=password",
success: function (atsakas) {
alert(atsakas);
},
error: function (error) {
alert("error");
}
});
Run Code Online (Sandbox Code Playgroud)
而且,从控制器我使用 HTTPClient 进行 POST 调用并从 XML 响应中获取所需的值。
[Authorize]
[Route("API/Gumtreetoken")]
public IActionResult GumtreePost(string user, string pasword)
{
string atsakas = "";
string token = "";
string id = "";
using (HttpClient client = new HttpClient())
{
//parametrai (PARAMS of your call)
var parameters = new Dictionary<string, string> { { "username", "YOURUSERNAME" }, { "password", "YOURPASSWORD" } };
//Uzkoduojama URL'ui
var encodedContent = new FormUrlEncodedContent(parameters);
try
{
//Post http callas.
HttpResponseMessage response = client.PostAsync("https://feed-api.gumtree.com/api/users/login", encodedContent).Result;
//nesekmes atveju error..
response.EnsureSuccessStatusCode();
//responsas to string
string responseBody = response.Content.ReadAsStringAsync().Result;
atsakas = responseBody;
}
catch (HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ", e.Message);
}
//xml perskaitymui
XmlDocument doc = new XmlDocument();
//xml uzpildomas api atsakymu
doc.LoadXml(@atsakas);
//iesko TOKEN
XmlNodeList xmltoken = doc.GetElementsByTagName("user:token");
//iesko ID
XmlNodeList xmlid = doc.GetElementsByTagName("user:id");
token = xmltoken[0].InnerText;
id = xmlid[0].InnerText;
atsakas = "ID: " + id + " Token: " + token;
}
return Json(atsakas);
}
Run Code Online (Sandbox Code Playgroud)
这应该是异步的,所以,你可以这样做:
[Authorize]
[Route("API/Gumtreetoken")]
public async Task<IActionResult> GumtreePost(string user, string pasword)
{
string atsakas = "";
string token = "";
string id = "";
using (HttpClient client = new HttpClient())
{
var parameters = new Dictionary<string, string> { { "username", "YOURUSERNAME" }, { "password", "YOURPASSWORD" } };
var encodedContent = new FormUrlEncodedContent(parameters);
try
{
HttpResponseMessage response = await client.PostAsync("https://feed-api.gumtree.com/api/users/login", encodedContent);
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
atsakas = responseBody;
}
catch (HttpRequestException e)
{
Console.WriteLine("\nException Caught!");
Console.WriteLine("Message :{0} ", e.Message);
}
XmlDocument doc = new XmlDocument();
doc.LoadXml(@atsakas);
XmlNodeList xmltoken = doc.GetElementsByTagName("user:token");
XmlNodeList xmlid = doc.GetElementsByTagName("user:id");
token = xmltoken[0].InnerText;
id = xmlid[0].InnerText;
atsakas = "ID: " + id + " Token: " + token;
}
return Json(atsakas);
}
Run Code Online (Sandbox Code Playgroud)