2011-02-16 70 views
0

我想構建一個HTTP發佈,它將發送數據並自動將數據綁定到模型中。但是,我有一個問題需要解決,因爲模型已經空了。我使用MVC 2C#,生成發送給MVC的HttpPost 2以模型作爲參數的動作

我控制器

[HttpPost] 
public JsonResult Authenticate(AuthenticateRequest request) 
{ 
    //...do stuff 
} 

,這裏是我如何建立請求。

private static string Url(string action, string controller) 
    { 
     return String.Format("{0}/{1}/{2}", Settings.Default.MobileServiceUrl, controller, action); 
    } 

    public static string Post(string action, string controller, NameValueCollection parameters) 
    { 
     string url = Url(action, controller); 

     using (WebClient client = new WebClient()) 
     { 
      NameValueCollection fields = new NameValueCollection(); 

      client.UploadValues(url, parameters); 

      byte[] respBytes = client.UploadValues(url, fields); 

      return client.Encoding.GetString(respBytes); 
     } 
    } 

這裏的模型類

public class AuthenticateRequest 
{ 
    public string SiteAbbreviation { get; set; } 
    public string Username { get; set; } 
    public string Password { get; set; } 
    public string AdminPassword { get; set; } 
} 

這裏是樣本數據

NameValueCollection fields = new NameValueCollection(); 
     fields.Add("SiteAbbreviation", "ABCD"); 
     fields.Add("Username", "username"); 
     fields.Add("Password", "password"); 
     fields.Add("AdminPassword", "password"); 

     var json = HttpRequestHelper.Post("Authenticate", "Account", fields); 

     var result = JsonConvert.DeserializeObject<AuthenticateRequest>(json); 

編輯:

如果你想知道爲什麼我這樣做,我的MVC應用程序是一個休息api,返回json的一切。我正在嘗試構建一個測試項目來測試我的控制器方法。

回答

2

假設:

public class AuthenticateRequest 
{ 
    public string SiteAbbreviation { get; set; } 
    public string Username { get; set; } 
    public string Password { get; set; } 
    public string AdminPassword { get; set; } 
} 

和:

[HttpPost] 
public ActionResult Authenticate(AuthenticateRequest request) 
{ 
    //...do stuff 
} 

以下最應該工作:

using (var client = new WebClient()) 
{ 
    var fields = new NameValueCollection 
    { 
     { "SiteAbbreviation", "ABCD" }, 
     { "Username", "username" }, 
     { "Password", "password" }, 
     { "AdminPassword", "password" } 
    }; 
    byte[] result = client.UploadValues(
     "http://foo.com/someController/authenticate", 
     fields 
    ); 
    // TODO: do something with the result 
    // if it is a JSON object deserialize it back to a model 
} 

一旦你確保這個工程(應該)你可以開始組裝這些代碼。

+0

呃,腦屁在那裏。謝謝Darin。 – Josh 2011-02-16 22:21:03

0

Got Error 404 in MVC 3。刪除[HttpPost]屬性後,上面的代碼工作正常。

相關問題