【问题标题】:How to make HTTP call from Controller ? to Use web API's Asp.Net Core C#如何从 Controller 进行 HTTP 调用?使用 Web API 的 Asp.Net Core C#
【发布时间】:2019-08-16 22:45:48
【问题描述】:

我想对各种服务进行 HTTP 调用,POST/GET/DELETE..,并读取响应 JSON 和 XML,如何在服务器端的 C# 中执行此操作?

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

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

【问题讨论】:

  • 只需使用 HttpClient 构建相同的请求服务器端或使用 RestSharp 或 Flurl 等 3rd 方构建
  • “API 调用”没有任何意义。 POST/GET 等是 HTTP 调用。 .NET Core 中的内置选项是 HttpClient。但是,您所说的 XML 服务是什么意思? SOAP 服务还是带有 XML 的 REST?在第一种情况下,您需要使用 WCF 从服务的 WSDL 文件生成代理。在第二个中,只需使用具有正确正文的 HttpClient
  • “客户端 Ajax 不起作用”,您能提供到目前为止您尝试过的代码吗?
  • 也许是一些示例代码,让我们开始提供帮助。
  • Alexander,你不能通过 ajax 进行跨域调用,对吗?,(我在某处读过它,因为安全原因你不能这样做。)从我自己的获取数据可以正常工作api.

标签: c# api asp.net-core asp.net-core-mvc


【解决方案1】:

使用ajax调用controler:

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

这应该是异步的,所以,你可以这样做:

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

【讨论】:

【解决方案2】:

试试这个代码: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);
            }
        }
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-27
    • 2018-12-30
    • 1970-01-01
    • 2019-11-04
    • 1970-01-01
    • 2022-11-21
    • 2016-10-14
    • 1970-01-01
    相关资源
    最近更新 更多