WebAPI POST,服务始终接收null

时间:2014-03-24 17:13:15

标签: c# android asp.net json asp.net-web-api

我一直在寻找这个问题的几个小时,但我似乎无法在任何地方找到任何答案

我已经构建了一个接受JSON GET / POST请求的ASP.NET WebAPI,当我使用fiddler或高级rest客户端扩展用于google chrome时,它可以运行A1。

现在我必须使用现有的Android应用程序并修改它以使用我的WebAPI。我已经清除了所有垃圾,我不需要让它变得更容易,但我仍然无法发布。 GET工作正常,我收到我的响应字符串,一切都很好,但POST返回400 Bad Request。

我的webApi控制器需要一个ProblemReports对象。问题报告由我做出,它是这样的:

    public class ProblemReports
{
    [Key]
    public int problem_id { get; set; }
    [Required]
    public Nullable<int> request_type { get; set; }
    [Required]
    public Nullable<int> problem_type_id { get; set; }
    public String picture_url { get; set; }
    public contact_information contact_information { get; set; }
    public problem_location problem_location { get; set; }
    public bool dog_on_property { get; set; }

}

带子类

    public class problem_location
{
    public String street { get; set; }
    public String city { get; set; }
    public int relative_position_id { get; set; }
    public double longitude { get; set; }
    public double latitude { get; set; }
}

    public class contact_information
{
    public String name { get; set; }
    public String phone { get; set; }
}

这是我的服务处理程序类中的android POST的代码 有趣的是,我可以在将json字符串发送到StringEntity之前放置一个断点,复制原始json字符串,将其粘贴到BODY部分高级休息客户端,填充标题,点击帖子和繁荣:响应是200 OK

如果我在控制器上断开了我的WebAPI,我可以看到,当通过高级休息客户端发送请求时,我可以访问问题报告,但如果我在我的Android应用程序的请求中断开它,则问题报告为空

public static String POST(String url, ProblemReports report) {
    InputStream inputStream = null;
    String result = "";

    if (report.picture_url == null)
    {
        report.picture_url = "no picture";
    }
    try {

        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        String json = "";
        JSONObject jsonObject = new JSONObject();
        jsonObject.accumulate("request_type", report.request_type);
        jsonObject.accumulate("problem_type_id", report.problem_type_id);
        jsonObject.accumulate("picture_url", report.picture_url);

        JSONObject contact_informationObject = new JSONObject();
        contact_informationObject.accumulate("name",
                report.contact_information.name);
        contact_informationObject.accumulate("phone",
                report.contact_information.phone);
        jsonObject.accumulate("contact_information",
                contact_informationObject);

        JSONObject problem_locationObject = new JSONObject();
        problem_locationObject.accumulate("street",
                report.problem_location.street);
        problem_locationObject.accumulate("city",
                report.problem_location.city);
        problem_locationObject.accumulate("latitude",
                report.problem_location.latitude);
        problem_locationObject.accumulate("longitude",
                report.problem_location.longitude);
        problem_locationObject.accumulate("relative_position_id",
                report.problem_location.relative_position_id);
        jsonObject.accumulate("problem_location", problem_locationObject);

        jsonObject.accumulate("dog_on_property", report.dog_on_property);

        json = jsonObject.toString();
        //String otherJson = "{ProblemReports: " + json + "}";
        //I saw on the web to add ProblemReports: but it doensn't work

        StringEntity se = new StringEntity(json);
        httpPost.setEntity(se);
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json; charset=utf-8");
        httpPost.setHeader(
                "Authorization",
                "Bearer TokenRemovedBecauseUseless");


        HttpResponse httpResponse = httpclient.execute(httpPost);
        inputStream = httpResponse.getEntity().getContent();

        if (inputStream != null)
            result = convertInputStreamToString(inputStream);
        else
            result = "InputStream convert fail!!";

    } catch (Exception e) {
        return e.getCause().toString();
    }

    return result;
}

这是从我的应用程序制作的原始JSON字符串。该实际字符串在Fiddler或高级休息客户端

上正常工作
{
"contact_information":
{
    "phone":"6666666666",
    "name":"fiber"
},
"dog_on_property":false,
"problem_type_id":3,
"request_type":1,
"problem_location":
{
    "longitude":1234,
    "latitude":1234,
    "relative_position_id":0,
    "city":"Montreal, QC A1A 1A1",
    "street":"0000 René-Lévesque Blvd"
}

}

我不知道这里发生了什么,任何帮助/提示/建议都会做。 我已经将我的控制器设置为抛出任何错误,我唯一得到的就是400 BAD REQUEST

这是我的控制器的帖子部分

 // POST api/ProblemReports
    [ResponseType(typeof(ProblemReports))]
    public IHttpActionResult PostProblemReports([FromBody]ProblemReports problemreports)
    {
        var allErrors = ModelState.Values.SelectMany(v => v.Errors);
        if (!ModelState.IsValid)
        {
            throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, this.ModelState));
          //  return BadRequest(ModelState);
        }

        try
        {
            db.ProblemReports.Add(problemreports);
            db.SaveChanges();
        }
        catch (Exception ex)
        {
            return Ok(ex);
        }


        //return CreatedAtRoute("DefaultApi", new { id = problemreports.problem_id }, problemreports);
        ReturnID ri = new ReturnID(problemreports.problem_id);
        return Ok(ri);
    }

1 个答案:

答案 0 :(得分:4)

找到我的问题的答案。花了4个小时才发现这个小错误,但在这里:

我有一行

 httpPost.setHeader("Content-type", "application/json; charset=utf-8")

和字符串实体

 StringEntity se = new StringEntity(json);

需要

 httpPost.setHeader("Content-type", "application/json") 

并且

 StringEntity se = new StringEntity(json, "UTF-8");

热潮一切正常,抱歉打扰任何人感谢阅读并度过愉快的一天