使用ajax将复杂且简单的参数发送到web api

问题描述 投票:0回答:1

我写web api。

web api控制器:

public class TaskApiController : ApiController
    {
     [HttpPost]
        public IHttpActionResult PostNewTask(string xx,string yy,CommonTask Task)
        {
    ...
    }
}

和ajax:

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”上未找到任何操作

ajax asp.net-web-api2 asp.net-web-api-routing
1个回答
0
投票
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>
© www.soinside.com 2019 - 2024. All rights reserved.