标签:
之前没做过Api接口开发,很少了解一下东西。今天遇到了很多问题。尤其是GET,POST时候提示404,405,等问题。
场景一:POST提交一个字段给后台标记为[HttpPost]的方法:
[HttpPost] [Route("SendCaptcha")] public HttpResponseMessage SendCaptchaSms([FromBody]string mobile) { return CreateResponse("", new SendSmsResult() { ReturnCode = -2, Message = "手机号码为空" }); }
<script>
var sendsmsCaptcha = function () {
var mobile = "13800138000";
$.ajax({
type: "POST",
url: "/Mobile/Captcha/SendCaptcha",
data: { "": mobile }, // 关键奇葩点就在这里,刚开始传递{"mobile":mobile}后台老是提示mobile为null
dataType: "json",
success: function (data) {
console.log(data);
}
});
};
</script>
场景二:前端传递多个字段,以及一个复杂对象(比如参数个数不确定),此时用dynamic比较方便
[HttpPost] [Route("SendNotifySms")] public HttpResponseMessage SendSms(dynamic dynamicData) { if (dynamicData == null) return CreateResponse("参数异常", "-1"); string mobile = ""; List<DynamicDict> extendParams; try { mobile = Convert.ToString(dynamicData.Mobile); extendParams = JsonHelper.ToObject<List<DynamicDict>>(Convert.ToString(dynamicData.extendParams)); } catch (Exception ex) { LogHelper.LogErr("【SendSms】" + ex.GetBaseException()); return CreateResponse("参数异常", "-1"); }
// 其他逻辑 }
前端JS调用:
<script> var sendsms = function () { var mobile = "13800138000"; var params = [ { "Key": "DealerShopName", "Value": "火星北京路4S店" }, { "Key": "TestDriverModelName", "Value": "大黄蜂 F11战斗机" }, { "Key": "TestDriverDate", "Value": "2016年7月28日 星期四" }, { "Key": "DealerShopAddress", "Value": "火星北京路4S店9527号" }, { "Key": "AdviserNameAndPhone", "Value": "东方不败:13838389438" } ]; $.ajax({ type: "POST", url: "/Mobile/Captcha/SendNotifySms", data: JSON.stringify({ "Mobile": mobile, "extendParams": params }), contentType: ‘application/json‘, // 这里一定不能忘掉了 success: function (data) { console.log(data); } }); }; </script>
折腾了一个小时,调试了好几次,终于算吧逻辑跑通了。真是知识匮乏时间成本高啊。
发现了一篇文章写的更详细:http://www.cnblogs.com/landeanfen/p/5337072.html
标签:
原文地址:http://www.cnblogs.com/hager/p/5715144.html