c# – 使用jQuery向Web API发布多个参数
发布时间:2020-12-15 05:38:51 所属栏目:百科 来源:网络整理
导读:像我之前的许多人一样,我正在尝试将多个参数传递给Web API项目.我尝试过在这个网站上提供的几种解决方案,但没有运气.我最近的失败迭代看起来如下: 控制器 public class UserDTO{ public int userID; public string username;}[HttpPost]public string Post(
像我之前的许多人一样,我正在尝试将多个参数传递给Web API项目.我尝试过在这个网站上提供的几种解决方案,但没有运气.我最近的失败迭代看起来如下:
控制器 public class UserDTO { public int userID; public string username; } [HttpPost] public string Post([FromBody]UserDTO userDTO) { return userDTO.userID.ToString() + " " + userDTO.username; } Web API路由配置 config.Routes.MapHttpRoute( name: "DefaultApi",routeTemplate: "api/{controller}/{id}",defaults: new { id = RouteParameter.Optional } ); jQuery var apiUrl = "http://localhost:55051/api/User/Post"; var userDTO = { userID: 5,username: "testuser" }; $.ajax({ type: "POST",url: apiUrl,data: JSON.stringify(userDTO),datatype: "json",contenttype: "application/json; charset=utf-8" )}; 小提琴输出 Fiddler显示正确传递的JSON变量,在Raw视图中我可以看到: { “用户ID”:5 “用户名”: “TESTUSER”} 关于执行 userID = 0 username = null 救命! 我认为问题出在Web API上,并且由于我的POST似乎在Fiddler中正确格式化,因此使用JSON参数很困难.有任何想法吗? 解决方法
你的jQuery ajax调用失败了吗?检查一下?
var apiUrl = "http://localhost:55051/api/UserController/Post"; 看到你的代码应该是: var apiUrl = "http://localhost:55051/api/User"; 单词控制器通常不是您的URL的一部分.您不必显式调用POST,它应该按照惯例选择它,因为您的ajax调用是POST. 编辑: 上面和你的ajax调用中的套管作为评论. 我个人使用Firebug(Firefox扩展)来调试这些案例.如果在这种情况下发现它比提琴手更方便. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |