首页 > 解决方案 > 使用 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' 上找不到与请求匹配的操作

标签: ajaxasp.net-web-api2asp.net-web-api-routing

解决方案


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>

推荐阅读