场景是,我必须从我的代码中调用一个服务,它向我返回一个HTML块,然后我需要执行该代码来重定向另一个页面。
代码为:
var request = (HttpWebRequest)WebRequest.Create("Destination URL");
request.Method = WebRequestMethods.Http.Post;
request.ContentType = MimeTypes.ApplicationXWwwFormUrlencoded;
request.ContentLength = postData.Length;
try
{
using (var stream = request.GetRequestStream())
{
stream.Write(postData, 0, postData.Length); //postData holds post parameters
}
var httpResponse = (HttpWebResponse)request.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var response = streamReader.ReadToEnd();
}
}
catch (Exception ex)
{
//Error handling
}在response变量中,我得到了以下响应:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript">
function closethisasap() {
document.forms["redirectpost"].submit();
}
</script>
</head>
<body onload="closethisasap();">
<form name="redirectpost" method="post" action="<redirection URL>">
</form>
</body>
</html>我花了很长时间寻找一种方法来运行这个HTML响应。但是还没有找到。
有没有办法运行超文本标记语言自动重定向到所需的目的地,或者解析超文本标记语言并抓取表单操作值并运行HttpContext.Response.Redirect("URL")?
发布于 2017-02-17 04:18:16
好的。在得到@David的建议后,我能够解析HTML并成功地重定向到所需的URL。以下是我的解决方案(在https://stackoverflow.com/a/847051/897504的帮助下):
HtmlDocument html = new HtmlDocument();
html.LoadHtml(streamReader.ReadToEnd());
// ParseErrors is an ArrayList containing any errors from the Load statement
if (html.ParseErrors != null && html.ParseErrors.Count() > 0)
{
// Handle any parse errors as required
}
else
{
if (html.DocumentNode != null)
{
HtmlNode formNode = html.DocumentNode.SelectNodes("//form[@action]").FirstOrDefault();
if (formNode != null)
{
HtmlAttribute att = formNode.Attributes["action"];
if (att != null)
_httpContext.Response.Redirect(att.Value);
else
_httpContext.Response.Redirect(storeLocation);
}
}
}非常感谢。
https://stackoverflow.com/questions/42280334
复制相似问题