使用.NET Framework 4.5在ASP.NET MVC 4中向WebApi传递JSON



我正在尝试从Restful API传递模型。我的代码是:

public class RestApiInvocations<T>
{
public HttpResponseMessage Post(string url, T model)
{
HttpResponseMessage result = null;
HttpClient client = new HttpClient();
try
{
result = client.PostAsJsonAsync(url, model).Result;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex);
}
return result;
}
}

在API控制器中,我在传入参数上添加了FromUriFromBody属性。

但是我的HttpClient对象不允许我添加Content-Type标头。我可以添加一个Accept头,所以我尝试用application/json添加一个Accept头,但没有结果。有什么建议吗?谢谢你的帮助!

private const string _Uri = "/ROUTE_TO_ACTION";
public ReturnModel AddInvoice(SomeModel model)
{
var uri = string.Format(_Uri);
var response = ServiceClient().PostAsJsonAsync(uri, model).Result;
var result = response.Content.ReadAsAsync<ReturnModel>().Result;
return result;
}
private HttpClient ServiceClient()
{
var client= new HttpClient();
client.BaseAddress = new Uri("YOUR_BASE_URL_TO_API");   //"http://localhost:8080/"
client.Timeout = TimeSpan.FromMinutes(3);
}

设置你的Urls/Endpoints并运行它。在编写代码之前,请在POSTMAN上测试Api端点。

最新更新