簡體   English   中英

如何從控制器進行 HTTP 調用? 使用 Web API 的 Asp.Net Core C#

[英]How to make HTTP call from Controller ? to Use web API's Asp.Net Core C#

我想對各種服務進行 HTTP 調用,POST/GET/DELETE..,並讀取響應 JSON 和 XML,如何在服務器端的 C# 中執行此操作?

簡而言之:如何從 Asp.Net Core C# 進行 Api 調用。

客戶端 Ajax 不起作用,(對於跨域)

使用ajax調用控制器:

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

試試這個代碼: 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);
            }
        }
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM