为什么我的web API post方法获取null参数?

时间:2015-03-02 11:51:25

标签: asp.net

我有一个带有这样的控制器的Web API项目:

namespace Api.Controllers
{

public class StudyController : ApiController
{
    [Route("api/PostReviewedStudyData")]
    [HttpPost]
    public bool PostReviewedStudyData([FromBody]string jsonStudy)
    {
       ApiStudy study = JsonHelper.JsonDeserialize<ApiStudy>(jsonStudy);
       BusinessLogics.BL.SaveReviewedStudyDataToDb(study); 
       return true;
    }

    [Route("api/GetStudyData/{studyUid}")]
    [HttpGet, HttpPost]
    public string GetStudyData(string studyUid)
    {
        ApiStudy study = BusinessLogics.BL.GetStudyObject(studyUid);
        return JsonHelper.JsonSerializer<ApiStudy>(study);
    }
}
}

我从另一个应用程序中这样称呼它:

HttpWebRequest httpWReq = (HttpWebRequest)WebRequest.Create(@"http://localhost:60604/api/PostReviewedStudyData");
ASCIIEncoding encoding = new ASCIIEncoding();
string postData = Api.JsonHelper.JsonSerializer<ApiStudy>(s);
byte[] data = encoding.GetBytes(postData);

httpWReq.Method = "POST";
httpWReq.ContentType = "application/json; charset=utf-8";
httpWReq.ContentLength = data.Length;
httpWReq.Accept = "application/json";

using (Stream stream = httpWReq.GetRequestStream())
{
    stream.Write(data, 0, data.Length);
}

HttpWebResponse response = (HttpWebResponse)httpWReq.GetResponse();

string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

我在post方法的断点被命中,但jsonStudy对象为null。任何想法?

2 个答案:

答案 0 :(得分:0)

首先我注意到的是:

HttpWebRequest httpWReq =    (HttpWebRequest)WebRequest.Create(@"http://localhost:60604/api/PostReviewedStudy Data");

你在PostReviewedStudy数据中也有空格如果不起作用尝试删除内容类型行并查看它是否有效

答案 1 :(得分:0)

尝试以下方法:

[Route("api/PostReviewedStudyData")]
[HttpPost]
public bool PostReviewedStudyData([FromBody]ApiStudy study)
{
   BusinessLogics.BL.SaveReviewedStudyDataToDb(study); 
   return true;
}

WebApi支持完全类型化的参数,无需从JSON字符串转换。