【问题标题】:Post JSON to mvc3 controller from WinForms App从 WinForms 应用程序将 JSON 发布到 mvc3 控制器
【发布时间】:2012-03-28 22:26:09
【问题描述】:

我在 ASP.NET MVC3 应用程序中有一个控制器/操作。它处理用户登录的发布请求。我正在尝试模拟,但来自桌面 winForms 应用程序。

我的控制器如下所示:

  [HttpPost]
  [AllowAnonymous]
  public virtual ActionResult LogOn(LogOnModel model, string returnUrl)
  {
    //authenticate user logic
  }

我正在以这种方式生成我的 HTTP 请求:

public static bool AuthenticateClient(客户端客户端,字符串用户名,字符串密码) { // 将这些字段名称更改为您的登录页面所期望的任何元素 字符串用户名字段 = 用户名; 字符串密码字段 = 密码;

        string loginUrl = "http://localhost/Account/LogOn/";

        // format login request
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(loginUrl);
        request.Method = "POST";
        request.ContentType = "application/x-www-form-urlencoded";
        request.AllowAutoRedirect = false;
        request.CookieContainer = new CookieContainer();

        // format and send login data
        string requestData = JSON.Serialize(new LogOnModel(usernameField, passwordField, false));

        StreamWriter sw = new StreamWriter(request.GetRequestStream());
        sw.Write(requestData);
        sw.Close();

        // get the login response
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        StreamReader sr = new StreamReader(response.GetResponseStream());
        string responseData = sr.ReadToEnd();
        sr.Close();

        // retrieve the session ID
        string sessionId = null;
        foreach (Cookie cookie in response.Cookies)
        {
            if (cookie.Name == AuthCookieName)
            {
                sessionId = cookie.Value;
            }
        }

        // could not authenticate
        if (sessionId == null)
        {
            return false;
        }

        // send the session ID with every request
        client.OnRequestCreated = (args) =>
        {
            args.Request.Headers["Cookie"] = string.Format("{0}={1}", AuthCookieName, sessionId);
        };
        return true;
    }

通常,我可以从 jQuery 发出 Ajax 请求,并将控制器操作所期望的相同对象参数(在本例中为 LogonModel)传递给它,但是,当我从桌面应用程序执行此操作时,它显示为 null我每次都在行动中。

所以我的问题是,如何从我的桌面 winforms 应用程序发出请求,并在控制器中填充对象 (LogonModel) 以便我进行身份验证?

【问题讨论】:

  • 代码解决方案:string requestData = string.Format("{0}={1}&{2}={3}&RememberMe=false&Login=Login", "UserName", Uri.EscapeDataString(username ), "密码", Uri.EscapeDataString(password));

标签: c# asp.net-mvc winforms


【解决方案1】:

(为了完整性...)

您永远无法确定自己的请求是否正确。就我个人而言,我发现使用Fiddler 监控和比较呼叫更容易,然后根据需要进行优化和模拟......

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-28
    • 2012-01-25
    • 2016-07-05
    相关资源
    最近更新 更多