[英]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.