我有下一个ApiController
public class ValuesController : ApiController { // GET /api/values public IEnumerable<string> Get() { return new string[] { "value1","value2" }; } public User CreateUser(User user) { user.Id = 1000; return user; } }
与下一个路线
routes.MapHttpRoute( name: "DefaultApi",routeTemplate: "api/{controller}/{action}/{id}",defaults: new { id = RouteParameter.Optional });
我想要使用这项服务.我可以使用第一种方法:
var client = new WebClient(); var result = client.DownloadString(@"http://localhost:61872/api/values/get");
但我不能消耗第二种方法.当我做下一个:
var user = new User() { Name = "user1",Password = "pass1" }; var json = Newtonsoft.Json.JsonConvert.SerializeObject(user); result = client.UploadString(@"http://localhost:61872/api/values/createuser",json);
我没有附加信息就抓住了下一个例外
The remote server returned an error: (500) Internal Server Error.
我有两个问题:
解决方法
如果您打算发送JSON请求,请确保已正确设置Content-Type请求标头,否则服务器不知道如何编码请求以及Api控制器操作所采用的用户参数为null:
using (var client = new WebClient()) { client.Headers[HttpRequestHeader.ContentType] = "application/json"; var user = new User() { Name = "user1",Password = "pass1" }; var json = Newtonsoft.Json.JsonConvert.SerializeObject(user); var result = client.UploadString(@"http://localhost:61872/api/values/createuser",json); }