从C#执行HTML脚本

时间:2017-02-16 17:03:25

标签: c# asp.net

场景是我要从我的代码中调用一个服务,它会向我返回一个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 
        }

在响应变量中,我得到以下响应:

<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响应的方法。但是还没找到。

有没有办法运行HTML以自动重定向到所需的目标位置或解析HTML并获取表单操作值并运行HttpContext.Response.Redirect("URL")

1 个答案:

答案 0 :(得分:0)

行。从@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);
                            }
                        }
                    }

非常感谢。