繁体   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