簡體   English   中英

如何從MVC 6.0和asp net core應用程序中的第三方rest API獲取數據

[英]How to get data from third party rest API in MVC 6.0 and asp net core application

我有一個帶有AnjularJs 2的asp net core 1.0.1項目,我從web api而不是sql數據庫獲取數據。 我在google上瀏覽了不同的文章,但是沒有得到最好的方法從asp.net核心應用程序調用http get,post,put和delete API,無論我是否能成功地在MVC 5中進行相同的調用,如下所示,任何人都可以指導什么相當於asp net core中的以下代碼?

public static HttpWebResponse Get(string requestUrl, Dictionary<string, string> headers, string contentType, string acceptType)
{
    //Create http Request
    HttpWebRequest httprequest = WebRequest.Create(requestUrl) as HttpWebRequest;

    //Add all headers.
    httprequest.ContentType = contentType;
    httprequest.Accept = acceptType;
    httprequest.UserAgent = System.Web.HttpContext.Current.Request.UserAgent.ToString();
    foreach (var header in headers)
        httprequest.Headers.Add(header.Key, header.Value);
    httprequest.Method = GET;

    //Get response
    HttpWebResponse response = httprequest.GetResponse() as HttpWebResponse;
    return response;
}

你很親密:

public static async Task<HttpWebResponse> Get(string requestUrl, Dictionary<string, string> headers, string contentType, string acceptType, string userAgent)
{
    //Create http Request
    HttpWebRequest httprequest = WebRequest.Create(requestUrl) as HttpWebRequest;
    //Add all headers.
    httprequest.ContentType = contentType;
    httprequest.Accept = acceptType;
    httprequest.Headers[HttpRequestHeader.UserAgent] = userAgent;
    foreach (var header in headers)
    {
        httprequest.Headers[header.Key] = header.Value;
    }

    httprequest.Method = "GET";
    //Get response
    HttpWebResponse response = await httprequest.GetResponseAsync() as HttpWebResponse;
    return response;
}

注意事項:

  1. 該方法必須是異步的,因為在.NET Core中沒有GetResponse()同步版本。 這意味着您還應該使調用此方法的控制器操作異步,以便您現在可以await Get方法的結果: public async Task<IActionResult> Index() { ... }
  2. 沒有更多的HttpContext.Current userAgent現在作為參數傳遞。 在你的控制器里你可以像這樣檢索它: string userAgent = this.Request.Headers["User-Agent"];

還要記住,在完成HttpWebResponse實例的使用后正確處理它是非常重要的。 確保在using語句中包含對此方法的調用:

using (var response = await Get(...))
{
    ...
}

暫無
暫無

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

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