asp.net httpClient发送json无法正常工作

时间:2018-04-25 15:35:17

标签: asp.net httpclient

我想从我的一个asp.net应用程序发送数据到另一个。我正在尝试使用HttpClient。

我的第一个申请:

public class PostVacanciesController : Controller
{
    public myEntity db = new myEntity();
    public const string sendAppURL = "http://localhost:51394/SecondApp/sendData";

    public ActionResult PostTest()
    {
        try
        {
            PostData dataPost = new PostData();

            // Some code to get PostData from database

            var myContent = JsonConvert.SerializeObject(dataPost);
            var buffer = System.Text.Encoding.UTF8.GetBytes(myContent);
            var byteContent = new ByteArrayContent(buffer);
            byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");

            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri(sendAppURL);
            var result = client.PostAsync("", byteContent).Result;

            return new HttpStatusCodeResult(HttpStatusCode.OK);
        } catch(Exception any)
        {
            return new HttpStatusCodeResult(HttpStatusCode.InternalServerError);
        }
    }
}

我的PostData模型:

public class PostData
{
    public int PropertyID { get; set; }
    public List<int> Units { get; set; } = null;
}

这是我的第二个应用程序,我尝试获取数据

public class SecondAppController : Controller
{

    [EnableCors(origins: "*", headers: "*", methods: "*")]
    [System.Web.Http.HttpPost]
    public ActionResult sendData(FeedData receiveData)
    { 
        // receiveData variable is wrong.
        // It is showing PropertyID = 0 and Units = null

        return new HttpStatusCodeResult(HttpStatusCode.OK);
    }
}

我的FeedData模型:

public class FeedData
{
    public int PropertyID { get; set; }
    public List<int> Units { get; set; } = null;
}

有谁知道它为什么不发送数据?如果我在调用第二个应用程序之前创建了一个断点,我可以看到它有数据要发送。

由于

1 个答案:

答案 0 :(得分:1)

更新操作以使用StringContent,因为您已经在序列化JSON字符串。

public const string sendAppURL = "http://localhost:51394/SecondApp/sendData";
static HttpClient client = new HttpClient() {
    BaseAddress = new Uri(sendAppURL)
};

public async Task<ActionResult> PostTest() {
    try {
        PostData dataPost = new PostData();

        // Some code to get PostData from database

        var json = JsonConvert.SerializeObject(dataPost);
        var content = new StringContent(json, Encoding.UTF8, "application/json");
        var response = await client.PostAsync("", content);

        return new HttpStatusCodeResult(response.StatusCode);
    } catch(Exception any) {
        return new HttpStatusCodeResult(HttpStatusCode.InternalServerError);
    }
}

请注意包含异步语法。

您需要验证您正在使用哪个HttpPost属性,因为第二个控制器具有[System.Web.Http.HttpPost],而它继承自使用System.Web.Mvc.Controller

[System.Web.Mvc.HttpPost]