【问题标题】:Request.Form empty post dataRequest.Form 空帖子数据
【发布时间】:2014-05-01 15:20:42
【问题描述】:

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

这是我的有效负载:

但是当我尝试使用时:

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);
}

【问题讨论】:

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


    【解决方案1】:

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

    [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 是一个可为空的整数。

    【讨论】:

    • 我想我找到了问题所在。应用程序/json 是帖子。
    • 您如何通过 $.ajax() 发出 POST 请求?您可能需要更改 contentType 值以满足您的需求。
    • $http angular 它会自动为您提供 contentType application/json
    • 你能把Angular $http代码的代码贴出来吗?
    猜你喜欢
    • 2014-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-31
    相关资源
    最近更新 更多