2013-02-26 41 views
1

我想從C#作爲參數傳遞JSON對象到一個MVC動作,但是當我收到它的價值變成了空傳遞JSON從C#

任何建議?

var url = "myurl"; 
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url); 
httpWebRequest.ContentType = "text/json"; 
httpWebRequest.Method = "POST"; 

using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) 
{ 
var jsonContent = "{\"addProfileInfo\":{\"Address\" : \"Add Profile\", \"Address2\" : \"add2\", \"ArabicAddress1\" : \"\", \"ArabicAddress2\" : \"\", \"ArabicContactPerson\" : \"\", \"ArabicFirstName\" : \"\", \"ArabicMiddleName\" : \"\", \"ArabicLastName\" : \"\", \"BirthDate\" : \"1998-01-22T00:00:00\", \"CSO\" : 120, \"CompanyActivityId\" : 1, \"ContactPerson\" : \"\", \"Corporate\" : \"No\", \"FaxNumber\" : \"\", \"FirstName\" : \"Add Profile\", \"GeographicalRegionId\" : 58, \"HomeNumber\" : \"0235731789\", \"LastName\" : \"Gamal\", \"LoggedInUserID\" : 1976819, \"MiddleName\" : \"AddProfile\", \"MobileNumber\" : \"01111122829\", \"NationalID\" : null, \"NationalityId\" : 1, \"OccupationId\" : 8, \"OfficeNumber\" : \"\", \"PagerNumber\" : \"0235731739\", \"ParentID\" : 1989567, \"PassportID\" : null, \"Password\" : \"DLDovk65\", \"SendNewsByMail\" : false, \"StateID\" : null, \"StatusID\" : 1, \"StatusReasonID\" : 1, \"TitleId\" : 4, \"UCID\" : \"1007102885\", \"UserAccountManagerID\" : 299489, \"UserComments\" : \"\", \"UserGender\" : 1, \"UserName\" : \"AP.902651\", \"UserPreferredEmail\" : \"[email protected]\", \"ZipCode\" : \"\"},\"sourceName\":\"LDNCRM\"}"; 

streamWriter.Write(jsonContent); 
} 
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); 
using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) 
{ 
var responseText = streamReader.ReadToEnd();    
Console.WriteLine(responseText); 
} 
+0

動作是否需要強類型參數?當它爲空時,通常意味着該類型不匹配。 – atbebtg 2013-02-26 17:22:35

+0

是的,它需要一個強類型的參數,但我實現了我自己的ObjectFilter從ActionFilterAttribute繼承,我將json轉換爲使用json網絡庫的強類型對象ActionExecutingContext filterContext參數爲null的問題 – hazem 2013-02-26 17:30:46

+0

@atbebtg和btw它正在從jquery ajax調用,但從C#它不我認爲我的問題與構建JSON對象 – hazem 2013-02-26 17:32:29

回答

0

是否可以只創建一個C#對象,在JSON功能包裹它,只是傳遞作爲參數傳遞給你沒有得到所有低級別使用JavaScript調用的ActionResult?

+0

這是一個比aswer更多的評論。將問題留給OP作爲對問題的評論,而不是將它們發佈爲答案 – 2013-02-26 18:11:00

0

我使用restsharp(http://restsharp.org/),我相信也可以通過NuGet使用。有了這個圖書館,我可以做到以下幾點:

var myObject = new MyActionParameterType();    
var client = new RestClient(ConfigurationManager.AppSettings["ApiBaseUrl"]); 

var request = new RestRequest("myurl", Method.POST); 
request.RequestFormat = DataFormat.Json; 
request.AddHeader("Content-Type", "application/json"); 
request.AddBody(myObject); 

var response = client.Execute(request); 
var content = response.Content; 

該庫從強類型對象的JSON字符串處理所有的轉換。