2015-03-02 89 views
1

我有这样的控制器的网络API项目:为什么我的web API post方法获取null参数?

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

我在邮局方法断点被击中,但jsonStudy对象为null。有任何想法吗?

回答

0

首先我注意到的是这样的:

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

你在PostReviewedStudy数据空间还,如果不工作尝试删除内容类型的线路,看看它是否工作

+0

谢谢奇诺,如果我删除内容类型,我得到不支持的数据类型异常。空间就在复制时。 – tal 2015-03-02 12:33:56

0

尝试如下:

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

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

相关问题