C#,使用模型作为参数生成发送到MVC 2 Action的HttpPost

时间:2011-02-16 22:00:55

标签: c# asp.net-mvc-2 post httpwebrequest

我想构建一个HTTP帖子,它将发送数据并自动将数据绑定到模型中。然而,我正在解决这个问题,因为模型是空的。我正在使用mvc 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 个答案:

答案 0 :(得分: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
}

一旦确定这有效(并且它应该),您就可以开始对这段代码进行组件化。

答案 1 :(得分:0)

Error 404获得MVC 3。删除[HttpPost]属性后,上面的代码运行正常。