REST WEB API POST方法,未调用参数

时间:2013-09-27 18:13:35

标签: http rest http-post asp.net-web-api

我已经构建了一个带有控制器的REST API,该控制器具有一个带有4个参数的POST方法 -

 [HttpPost]
    public void SaveSession([FromBody] string userId, [FromBody] DateTime issueDateTime, [FromBody] string browserType, [FromBody] string salt)
    {
        // Params need to be changed
        _sessionService.SaveSession(userId, issueDateTime, browserType, salt);
    }

我应该如何在客户端发布数据,我的意思是应该发送的数据格式是什么?

我试过这种格式 -

"userId=abc&DateTime=someDatetime&browserType=somebrowser&salt=somesalt"

如果我尝试这样做就无法工作了,甚至没有调用Web服务方法

有人能告诉我正确的格式吗?

编辑: 以下是我调用API的方法 -

            const string endPoint = @"http://localhost:85/session/Test";
            var postData = "userId=abc&DateTime=someDatetime&browserType=somebrowser&salt=somesalt"
            var request = (HttpWebRequest) WebRequest.Create(EndPoint + parameters);
            request.Method = "POST";
            request.ContentLength = 0;
            request.ContentType = "application/x-www-form-urlencoded";

            if (!string.IsNullOrEmpty(postData) && Method == HttpVerb.POST)
            {
                var encoding = new UTF8Encoding();
                var bytes = Encoding.GetEncoding("iso-8859-1").GetBytes(postData);
                request.ContentLength = bytes.Length;

                using (var writeStream = request.GetRequestStream())
                {
                    writeStream.Write(bytes, 0, bytes.Length);
                }
            }

            using (var response = (HttpWebResponse) request.GetResponse())
            {
                var xmlDoc = new XmlDocument();

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    var message = String.Format("Request failed. Received HTTP {0}", response.StatusCode);
                    throw new ApplicationException(message);
                }

                // grab the response
                var responseStream = response.GetResponseStream();
                if (responseStream != null)
                {
                    xmlDoc.Load(responseStream);
                }
                return (xmlDoc);
            }

谢谢!

2 个答案:

答案 0 :(得分:0)

我假设路由已正确配置。

这样说....控制器方法中的DateTime参数已被命名为“issueDateTime”,而在请求中已被命名为“DateTime”。

答案 1 :(得分:0)

我知道,我在做什么错。我在WebService方法中发送了4个参数。我们只能在调用Web服务方法时发送一个参数。如果要发送多个数据,只需将其作为对象发送即可。像这样 -

[HttpPost]
public void SaveSession([FromBody] Values value)
{
    var userId = values.userId,
    var issueDateTime= values.issueDateTime,
    var browserType= values.browserType,
    var salt= values.salt,

    _sessionService.SaveSession(userId, issueDateTime, browserType, salt);
}