2015-03-02 120 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字符串轉換。

相關問題