Request.Form空帖数据

时间:2014-05-01 15:20:43

标签: c# asp.net-mvc request.form

尝试使用Request.Form来获取已发布的有效负载,但Request.Form总是{}为空?

这是我的有效负载:

chromepayload

但是当我尝试使用时:

var responseBytes = Request.HttpMethod == "POST" ? client.UploadValues(url, Request.Form) : client.DownloadData(url);

我的有效负载Request.Form为空。

整个C#代码:

public ActionResult Index(string pathInfo)
{
    var url = Settings.GetValue<string>("QualService") + "/" + pathInfo + "?" + Request.QueryString;

    //Get stuff from the back end
    using (var client = new WebClient())
    {
        client.Headers[HttpRequestHeader.ContentType] = "application/json";
        client.Headers[HttpRequestHeader.Cookie] = Request.Headers["Cookie"];
        client.Headers[HttpRequestHeader.Authorization] = "Basic " +
                                                          Convert.ToBase64String(
                                                              Encoding.UTF8.GetBytes(
                                                                  "x:{0}".Fmt(UserSession.ApiKey)));
        try
        {
            var responseBytes = Request.HttpMethod == "POST" ? client.UploadValues(url, Request.Form) : client.DownloadData(url);

            var result = new ContentResult();
            result.Content = Encoding.UTF8.GetString(responseBytes);
            result.ContentEncoding = Encoding.UTF8;
            result.ContentType = "application/json";
            return result;
        }
        catch(Exception e)
        {
            Logger.Error("Error while proxying to the API:  ", e);
        }
    }

    return Json(false);
}

1 个答案:

答案 0 :(得分:0)

我会保持简单。更改操作方法的签名:

[HttpPost]
public ActionResult Index(string pathInfo, string Id, string Name, int ProjectId)
{
    // ID, Name and ProjectId will be populated with the values in the payload.
    // ... Rest of code.

}

指定[HttpPost]将对您有所帮助,因为MVC模型绑定器(负责从例如Request.Form获取数据的类)将通过将其名称与Request.Form中的数据匹配来填充参数值。

注意,我不知道Id是数字还是字符串值。如果它是一个数字,那么你需要

[HttpPost]
public ActionResult Index(string pathInfo, int? Id, string Name, int ProjectId)
{

在这种情况下,Id是可以为空的整数。