从WinForms App将JSON发布到mvc3控制器

时间:2012-03-12 14:00:58

标签: c# asp.net-mvc winforms

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

我的控制器看起来像这样:

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

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

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

        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请求并传递与Controller Action期望的相同的对象参数(在本例中为LogonModel),但是,当我从桌面应用程序执行此操作时,它会显示每次在行动中我都为空。

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

1 个答案:

答案 0 :(得分:0)

(完整性......)

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