1

我正在尝试将 c# 中的 json 对象作为参数传递给 mvc 操作,但是当我收到它时,它的值变为 null

有什么建议吗?

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\" : \"AddProfile1@Domain.com\",  \"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);
}
4

2 回答 2

0

是否可以只创建一个 C# 对象,将其包装在 Json 函数中,然后将其作为参数传递给您正在调用的 ActionResult 而无需使用 javascript 获得所有低级别?

于 2013-02-26T17:49:13.657 回答
0

我使用我相信也可以通过 NuGet 获得的restsharp ( http://restsharp.org/ )。使用这个库,我可以执行以下操作:

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 字符串的所有转换。

于 2013-02-26T18:06:38.593 回答