[Azure Function]替代YQL service

YQL service于2019年1月3日停掉了,原来使用YQL来跨域访问的一个XML,现在不能用了。于是想要使用Azure Function,写一个service,然后发布到自己的同源的URL上面。
在这里插入图片描述
我们可以参考下面的链接:
https://docs.microsoft.com/en-us/azure/azure-functions/functions-create-your-first-function-visual-studio

在这个基础上面,建了GetRSSFeedNews项目,Function name改为GetRSSFeed,把Function1.cs改成下面这样:


using System.IO;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Azure.WebJobs.Host;
using Newtonsoft.Json;
using System.Xml;
using System.Net;
using System.Text;

namespace GetRSSFeedNews
{
    public static class Function1
    {
        [FunctionName("GetRSSFeed")]
        public static IActionResult Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]HttpRequest req, TraceWriter log)
        { 
            log.Info(req.Path);
            
            //访问XML页面,得到response
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://XXXX.XX.com/rssFeed.xml");
            request.Proxy = null;
            request.KeepAlive = false;
            request.Method = "GET";
            request.ContentType = "application/json; charset=UTF-8";
            request.AutomaticDecompression = DecompressionMethods.GZip;

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
            string retString =myStreamReader.ReadToEnd();
            
            myStreamReader.Close();
            myResponseStream.Close();

            if (response != null)
            {
                response.Close();
            }
            if (request != null)
            {
                request.Abort();
            }
            
			//因为得到的是XML,要转换成JSON
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(retString);
            string jsonText = JsonConvert.SerializeXmlNode(doc);
            
			//返回JSON
            return (ActionResult)new OkObjectResult(jsonText); 
        }
    }
}

展开阅读全文

没有更多推荐了,返回首页