【问题标题】:Properly simulating an HTML action in MVC ASP.NET在 MVC ASP.NET 中正确模拟 HTML 动作
【发布时间】:2013-06-01 09:29:49
【问题描述】:

我需要在 HTML 中模拟一个简单的动作,这个 HTML 实际上可以满足我的目的,但我必须在 MVC ASP.NET 中进行相同的动作。

这是 HTML:

<HTML>
<HEAD>
</HEAD>
    <BODY>
        <FORM method="post" autocomplete="off" ACTION="https://<target IP>/auth/index.html/u">
        Username:<BR>
        <INPUT type="text" name="user" accesskey="u" SIZE="25" VALUE="">
        <BR>
        Password:<BR>
        <INPUT type="password" name="password" accesskey="p" SIZE="25" 
        VALUE="">
        <BR>
        <INPUT type="submit">
        </FORM>
    </BODY>

此 HTML 获取两个参数“用户”和“密码”并将它们发布到 URI。我在我的应用程序中尝试了“GET”和“POST”两种方法,但没有成功。 这是我在 MVC ASP.NET 中的控制器:

    [AllowAnonymous]
    [HttpPost]
    public ActionResult Login(LoginModel model)
    {
        if (ModelState.IsValid)
        {
            string ArubaPost = "user=" + model.user + "&password=" + model.password;
            string ArubaURI = "https://<target IP>/auth/index.html/u";
            // this is to bypass the SSL certiface, not sure if it is needed
            System.Net.ServicePointManager.CertificatePolicy = new MyPolicy();

            // web request
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(ArubaURI);
            request.KeepAlive = false;
            request.AllowAutoRedirect = false;
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            byte[] postBytes = Encoding.Default.GetBytes(ArubaPost);
            request.ContentLength = postBytes.Length;
            Stream requestStream = request.GetRequestStream();
            requestStream.Write(postBytes, 0, postBytes.Length);
            requestStream.Close();

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream resStream = response.GetResponseStream();


            string location = response.Headers[HttpResponseHeader.Location];
            return Redirect(ArubaURI + location);

        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

我也尝试了“GET”操作,但结果是一样的。我实际上没有收到任何错误,当它在浏览器中运行时,我可以看到使用 Chrome 检查元素发送的请求带有状态代码 200。 这是一个网络控制器将所有流量重定向到它的页面,然后用户必须输入用户名和密码。然后当它通过 POST 或 GET 发送时,网络控制器必须捕获参数并验证它们。如果验证成功,网络控制器会将用户重定向到他最初请求的页面,以便他可以上网。那个简单的 HTML 页面实现了所有这些,但在 MVC 应用程序中,我一次又一次地重定向到同一个登录页面。 有什么想法有什么问题吗?

【问题讨论】:

    标签: c# html asp.net-mvc http-post


    【解决方案1】:

    它不起作用,因为身份验证 cookie 未存储在浏览器中。而是将其交给您的服务器(MVC 应用程序)。

    以您当前的方法,您将无法实现您的目标。因为即使您的服务器将这些 cookie 提供给客户端(浏览器),它也不会起作用,因为这些 cookie 只会发送到您的服务器,而不是 &lt;target IP&gt; 服务器。

    【讨论】:

    • 谢谢,那么有什么可能的方法来做到这一点?
    • 根据我的猜测,我认为您可以使用 http 代理服务器来满足您的需求。您可以查看此问题的答案:stackoverflow.com/questions/9276055/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-08
    • 2013-11-07
    • 1970-01-01
    • 2010-10-22
    相关资源
    最近更新 更多