前言
webapi 傳值和mvc略有不同,一不小心容易出錯,簡單總結webapi傳值。
按照mvc方式傳值會出錯415
1、mvc傳值
function mvcPassValue() { var user = { Age: 6, Username: "hurne", remark: "hehe" } var muenmodel = { id: 3, url: "url", User: JSON.stringify(user) }; var Testclass = { id : 1, name : "datong", muen : muenmodel }; $.ajax({ type: "post", url: "@Url.Action("testentity")", data: Testclass, success: function () { alert(0); } }); }
//action [HttpPost] public JsonResult testentity(Testclass model) { var userInfo = JsonConvert.DeserializeObject<userinfo>(model.Muen.user); return Json(new { data = model }); } //實體類 public class Testclass { public int Id { get; set; } public string Name { get; set; } public muen Muen { get; set; } } public class muen { public int Id { get; set; } public string url { get; set; } public string user { get; set; } } public class userinfo { public int age { get; set; } public string userName { get; set; } public string Remark { get; set; } }
后台正常接收
2、webapi 傳值
前段代碼:修改為對應的webapi后台地址
[HttpPost, Route("testentity")] public object testentity(Testclass model) { var userInfo = JsonConvert.DeserializeObject<userinfo>(model.Muen.user); return new { data = model }; }
運行結果 我擦出錯了報 415
{"message":"The request entity's media type 'application/x-www-form-urlencoded' is not supported for this resource.","exceptionMessage":"No MediaTypeFormatter is available to read an object of type 'Testclass' from content with media type 'application/x-www-form-urlencoded'.","exceptionType":"System.Net.Http.UnsupportedMediaTypeException","stackTrace":" 在 System.Net.Http.HttpContentExtensions.ReadAsAsync[T](HttpContent content, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)\r\n 在 System.Web.Http.ModelBinding.FormatterParameterBinding.ReadContentAsync(HttpRequestMessage request, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)"}
大意是說不支持application/x-www-form-urlencoded 數據類型

那就從content-Type着手查閱資料
解決方法如下
修改content-Type 如下

運行測試--》運行正常
3、后台調用 api 傳值
ScanResultModel model = new ScanResultModel(); model.Data = new List<SubmitOnlineStateModelItem>(); model.Flag = true; model.RecordId = 2; model.TaskLogId = 33; string callback = "/api/action/method"; string url = "http://localhost:14407/"; var client = new RestClient(url + callback); //從發出請求開始算起,到與服務器建立連接的時間 client.Timeout = 60 * 1000; //ReadWriteTimeout設置的是從建立連接開始,到下載數據完畢所歷經的時間 client.ReadWriteTimeout = 60 * 1000; var request = new RestRequest( Method.POST); request.AddHeader("Content-Type", "application/json; charset=utf-8"); request.Parameters.Clear(); request.AddParameter("application/json", JsonConvert.SerializeObject(model), ParameterType.RequestBody); IRestResponse response = client.Execute(request); var content = response.Content; if (response.ErrorException != null) { return new { flag = true, msg = response.ErrorException.Message }; } return new {flag = true,msg = content };
調用 api 方法
public object ScanAllIp(ScanResultModel resultModel) { .............. }
-
總結
webapi傳值:
1、設置 content-Type = ‘appliaction/json’
2、傳值(data)轉換為字符串 JSON.stringify(data)
3,mvc 的 action 和 webapi 方法,可以接受樹形參數傳值
4、mvc和webapi參數名不區分大小寫,newtonsoft.json 也不區分大小寫
