从Android到Web API的POST数据返回404

Din*_*uka 1 asp.net rest android asp.net-web-api azure-mobile-services

我正在尝试将来自我的Android客户端的数据作为POST请求发送到我的Web API后端,但它返回404响应代码.这是我的代码:

后端:

[HttpPost]
[Route("api/postcomment")]
public IHttpActionResult PostComment(string comment, string email, string actid)
{
       string status = CC.PostNewComment(comment, email, actid);
       return Ok(status);
}
Run Code Online (Sandbox Code Playgroud)

Android代码:

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://MYWEBADDRESS.azure-mobile.net/api/postcomment");
String mobileServiceAppId = "AZURE_SERVICE_APP_ID";

try {

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("comment", comment));
        nameValuePairs.add(new BasicNameValuePair("email", currEmail));
        nameValuePairs.add(new BasicNameValuePair("actid", currActID));

        httppost.setHeader("Content-Type", "application/json");
        httppost.setHeader("ACCEPT", "application/json");
        httppost.setHeader("X-ZUMO-APPLICATION", mobileServiceAppId);

        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairs);
        httppost.setEntity(formEntity);

        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);

} 
catch (Exception e) {
}
Run Code Online (Sandbox Code Playgroud)

但是,这会将404响应代码返回给我的Android客户端.我的代码不正确吗?请指出错误:)

Din*_*uka 5

我通过正确设置我的后端来接受Android客户端发送的参数来解决这个问题.问题出在我的后端,而不是我的客户端.

这是我的后端:

[Route("api/postcomment")]
public IHttpActionResult PostComment([FromBody] CommentViewModel model)
{
       string comment = model.Comment;
       //Do your processing
       return Ok(return_something);
}

public class CommentViewModel
{
        public string Comment { get; set; }
        public string Email { get; set; }
        public string Actid { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我使用[FromBody]强制方法读取请求体,我使用模型来获取客户端传递的值.该方法自动从请求中获取值并将它们设置为模型,使其变得非常容易.

请确保您的Android客户端正确地使用正确的POST代码传递您的参数.