如何从控制器进行HTTP调用?使用web API';Net核心C#

如何从控制器进行HTTP调用?使用web API';Net核心C#,c#,api,asp.net-core,asp.net-core-mvc,C#,Api,Asp.net Core,Asp.net Core Mvc,我想对各种服务进行HTTP调用,POST/GET/DELETE..,并读取JSON和XML响应,如何在服务器端的C#中实现这一点 简而言之:如何从Asp.Net核心C#进行Api调用 客户端Ajax不起作用(对于跨域)请尝试以下代码:从Asp.Net核心服务器端(C#)调用Api。 使用系统; 使用System.Collections.Generic; 使用System.Linq; 使用System.Net.Http; 使用System.Threading.Tasks; 使用Microsoft.

我想对各种服务进行HTTP调用,POST/GET/DELETE..,并读取JSON和XML响应,如何在服务器端的C#中实现这一点

简而言之:如何从Asp.Net核心C#进行Api调用


客户端Ajax不起作用(对于跨域)

请尝试以下代码:
从Asp.Net核心服务器端(C#)调用Api。

使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用System.Net.Http;
使用System.Threading.Tasks;
使用Microsoft.AspNetCore.Mvc;
命名空间core.api.Controllers
{
[路由(“api/[控制器]”)]
[ApiController]
公共类值控制器:控制器库
{
[HttpGet]
公共异步任务Get()
{
字符串url=”https://jsonplaceholder.typicode.com/todos“;//示例url
使用(HttpClient=new HttpClient())
{
返回wait client.GetStringAsync(url);
}
}
}

}使用ajax调用Controller:

$.ajax({                                        
        type: "GET",      
        url: "/API/Gumtreetoken?user=username&pasword=password",                                       
        success: function (atsakas) {                                       
              alert(atsakas);
        },
        error: function (error) {
              alert("error");         
        }
});
并且,从控制器中,我使用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);
    }
[授权]
[路线(“API/Gumtreetoken”)]
公共IActionResult GumtreePost(字符串用户、字符串密码)
{
字符串atsakas=“”;
字符串标记=”;
字符串id=“”;
使用(HttpClient=new HttpClient())
{
//parametri(您呼叫的参数)
var参数=新字典{{“username”、“YOURUSERNAME”}、{“password”、“YOURPASSWORD”};
//Uzkodoujama URL'ui
var encodedContent=新表单URLEncodedcontent(参数);
尝试
{
//Post http调用。
HttpResponseMessage响应=client.PostAsync(“https://feed-api.gumtree.com/api/users/login“,encodedContent)。结果;
//nesekmes atveju错误。。
response.EnsureSuccessStatusCode();
//对字符串的响应
字符串responseBody=response.Content.ReadAsStringAsync().Result;
atsakas=响应体;
}
捕获(HttpRequestException e)
{
Console.WriteLine(“\n异常被捕获!”);
WriteLine(“Message:{0}”,e.Message);
}
//xml个人用户界面
XmlDocument doc=新的XmlDocument();
//xml uzpildomas api atsakymu
doc.LoadXml(@atsakas);
//iesko代币
XmlNodeList xmltoken=doc.GetElementsByTagName(“用户:令牌”);
//iesko ID
XmlNodeList xmlid=doc.GetElementsByTagName(“用户:id”);
token=xmltoken[0]。InnerText;
id=xmlid[0]。InnerText;
atsakas=“ID:+ID+”令牌:+Token;
}
返回Json(atsakas);
}
这应该是异步的,因此,您可以这样做:

    [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);
    }
[授权]
[路线(“API/Gumtreetoken”)]
公共异步任务GumtreePost(字符串用户,字符串密码)
{
字符串atsakas=“”;
字符串标记=”;
字符串id=“”;
使用(HttpClient=new HttpClient())
{
var参数=新字典{{“username”、“YOURUSERNAME”}、{“password”、“YOURPASSWORD”};
var encodedContent=新表单URLEncodedcontent(参数);
尝试
{
HttpResponseMessage响应=等待客户端。PostAsync(“https://feed-api.gumtree.com/api/users/login“,编码内容);
response.EnsureSuccessStatusCode();
string responseBody=wait response.Content.ReadAsStringAsync();
atsakas=响应体;
}
捕获(HttpRequestException e)
{
Console.WriteLine(“\n异常被捕获!”);
WriteLine(“Message:{0}”,e.Message);
}
XmlDocument doc=新的XmlDocument();
doc.LoadXml(@atsakas);
XmlNodeList xmltoken=doc.GetElementsByTagName(“用户:令牌”);
XmlNodeList xmlid=doc.GetElementsByTagName(“用户:id”);
token=xmltoken[0]。InnerText;
id=xmlid[0]。InnerText;
atsakas=“ID:+ID+”令牌:+Token;
}
返回Json(atsakas);
}

只需使用HttpClient构建相同的请求服务器端,或使用第三方构建,如RestSharp或Flurl“API调用”并不意味着什么。POST/GET等是HTTP调用。NET内核中的内置选项是HttpClient。但是,您所说的XML服务是什么意思?SOAP服务还是使用XML的REST?在第一种情况下,您需要使用WCF从服务的WSDL文件生成代理。在第二个例子中,只需使用具有正确主体“客户端Ajax不起作用”的HttpClient,您能提供您迄今为止尝试过的代码吗?也许是一些示例代码,让我们开始帮助。Alexander,您不能通过Ajax进行跨域调用,对吗?(我在某个地方读过,由于安全原因,您不能这样做。)获取数据很好,从我自己的api。
    [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);
    }