我必须从其他网站获取html响应并加载到我的应用程序。我在下面写了代码,
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
namespace MVC_TEST.Controllers
{
public class DocumentCloudController : Controller
{
public string Index()
{
var result = GetResponse();
return result;
}
private static string GetResponse()
{
var html = string.Empty;
const string url = @"http://localhost/xxxxx/yyyyy/logon.aspx";
var request = (HttpWebRequest)WebRequest.Create(url);
request.AutomaticDecompression = DecompressionMethods.GZip;
using (var response = (HttpWebResponse)request.GetResponse())
{
using (var stream = response.GetResponseStream())
{
if (stream != null)
{
using (var reader = new StreamReader(stream))
{
html = reader.ReadToEnd();
}
}
}
}
return html;
}}
}
}
正确加载控件,但image,css和js路径映射到相对路径
/xxxx/yyyy/dojo.js ,
/xxxx/style/logon.css,
/xxxx/images/logon.png
在html中,我必须将其更改为实际网址,如下所示
http://localhost/xxxx/yyyy/dojo.js ,
http://localhost/xxxx/style/logon.js ,
http://localhost/xxxx/images/logon.png
一个选项是在html中找到这些内容替换它。
还有其他选项可以动态更改网址吗? IIS URL重写模块是否适合我的要求?
请分享您的想法
答案 0 :(得分:1)
使用IIS URL重写模块可以工作,但我建议使用像HTML Agility Pack或AngleSharp这样的HTML解析器来查询和操作DOM。
以下示例是在创建反向代理时为我工作的代码段:
foreach (var link in document.DocumentNode.SelectNodes("//link[@href]"))
{
var orgHrefValue = link.GetAttributeValue("href", string.Empty);
var updHrefValue = string.Concat("[BASE URL]", GetAbsoluteUrlString(requestedUrl, orgHrefValue).AbsoluteUri);
link.SetAttributeValue("href", updHrefValue);
}
private static Uri GetAbsoluteUrlString(string baseUrl, string url)
{
var uri = new Uri(url, UriKind.RelativeOrAbsolute);
if (!uri.IsAbsoluteUri)
uri = new Uri(new Uri(baseUrl), uri);
return uri;
}