[英]How to do Dynamic URL Redirect in ASP.net MVC?
我必须从另一个网站获取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;
}}
}
}
控件已正确加载,但是图像,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中找到这些内容替换它。
还有其他选项可以动态更改url吗? IIS URL重写模块是否适合我的要求?
请分享您的想法
使用IIS URL重写模块可以工作,但我建议使用HTML解析器(例如HTML Agility Pack或AngleSharp)来查询和操作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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.