ajax - 使用 ajax 向 web api 发送复杂和简单的参数
问题描述
我写网络API。
网络 API 控制器:
public class TaskApiController : ApiController
{
[HttpPost]
public IHttpActionResult PostNewTask(string xx,string yy,CommonTask Task)
{
...
}
}
和阿贾克斯:
var task = new Object();
task.Description = 'kjk';
task.ID = null;
var req = $.ajax({
url: 'http://localhost:3641/api/TaskApi',
contentType: "application/json",
data: {"xx":'admin',"yy":'123',"task": JSON.stringify(task) },
type: 'Post',
success: function (data) {
alert('success');
}
});
req.fail(function (jqXHR, textStatus) {
alert("Request failed: " + jqXHR.responseText);
});
和 WebApiConfig:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
运行 ajax 时,返回错误: 在控制器 'TaskApi' 上找不到与请求匹配的操作
解决方案
Always feed the POST methods with class type parameters. Please do the following modification on the API and JavaScript.
1. Create a model class
<pre>
public class Model
{
public string xx { get; set; }
public string yy { get; set; }
public CommonTask Task { get; set; }
}
</pre>
Then modify your Web API to accept a type of your class model
<pre>
public class TaskApiController : ApiController
{
[HttpPost]
public IHttpActionResult PostNewTask([FromBody] Model model)
{
}
}
</pre>
Change your ajax method to pass a json object similar to the Model class
<pre>
var task = new Object();
task.Description = 'kjk';
task.ID = null;
var data = {
"xx": 'admin',
"yy": '123',
"task" : JSON.stringify(task)
};
var req = $.ajax({
url: 'http://localhost:3641/api/TaskApi',
contentType: "application/json",
data: {"model": JSON.stringify(data) },
type: 'Post',
success: function (message) {
alert('success');
}
});
req.fail(function (jqXHR, textStatus) {
alert("Request failed: " + jqXHR.responseText);
});
</pre>
推荐阅读
- image-processing - 解释无符号短深度图值
- python - Tkinter:鼠标离开gui应用程序的显示区域后如何跟踪鼠标位置?
- react-native - 我正在尝试使用 react-native 在 TextInput 中实现文本更改和编辑结束,但它不太有效。谁能帮我?
- java - org.gradle.process.internal.ExecException: Process 'command 'xx/jdk-11.0.12.jdk/Contents/Home/bin/java'' 以非零退出值 1 结束
- python-3.x - 在 Python Quart 服务器中制作 URL 请求参数全局变量
- amazon-web-services - 适用于 SES 的 AWS CLI 版本 1 更新黑名单
- django - Django Cookies 未在浏览器中设置但在邮递员中工作 - Django Rest Framework
- excel - 结合 CONCAT、DATEDIF 和嵌套的 IF - 得到 #VALUE!错误
- java - 如何在创建 pdf 时在图像之间添加空格 - Android
- kubernetes - 在 gitlab CI 中连接到 kubernetes 集群时出现禁止错误