在 ASP.NET MVC 5 中使用 jquery AJAX 调用 Web API 出现错误
Call Web API using jquery AJAX in ASP.NET MVC 5 getting error
我将网络 api 添加到可用的项目中。
我的 api 控制器:
namespace MyApplication.Controllers
{
public class TaskApiController : ApiController
{
[HttpPost]
public IHttpActionResult Create(string UserName, string Password, string DoingDateTime, int ReferenceFrom, int ReferenceTo, string MaturityDateTime = "", int? PersonCompany_AffiliationID = null, int? SubjectID = null, string Description = "", int? ImportanceDegreeID = null, int? StatusID = null, int CompletionPercentage = 0, int? DossierID = null)
{
...
return Ok();
}
}
}
WebApiConfig.cs:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
将以下代码添加到 web.config:
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept,Authorization" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>
</system.webServer>
和ajax:
$.ajax({
url: 'localhost:3641/api/TaskApi',
contentType: 'application/x-www-form-urlencoded',
dataType: 'json',
data: {
UserName: 'admin',
Password: '123',
Description: 'test',
DoingDateTime: '1397/12/10',
ReferenceFrom: 2,
ReferenceTo: 2
},
type: 'Post',
success: function (data) {
alert('success');
}
, error: function (response) {
alert(response.responseText);
}
});
当我在浏览器中测试 Web api 时:
它工作正常。但是当 aun ajax 它 return 错误和 response.responseText returns "undefined".
解决问题的最快捷、最简洁的方法是创建视图模型。
另外请记住,对于 复杂类型 Web Api 默认情况下使用媒体类型格式化程序从邮件正文中读取值。
public class TaskViewModel
{
public string UserName { get; set; }
public string Password { get; set; }
public string DoingDateTime { get; set; }
public int ReferenceFrom { get; set; }
public int ReferenceTo { get; set; }
public string MaturityDateTime { get; set; }
public int? PersonCompany_AffiliationID { get; set; }
public int? SubjectID { get; set; }
public string Description { get; set; }
public int? ImportanceDegreeID { get; set; }
public int? StatusID { get; set; }
public int CompletionPercentage { get; set; }
public int? DossierID { get; set; }
}
[HttpPost]
public IHttpActionResult Create(TaskViewModel taskViewModel)
{
if (!ModelState.IsValid)
{
return BadRequest("");
}
return Ok();
}
用你的class写了一个AJAX,还是失败了
var task = new Object();
task.Description = 'kjk';
task.PersonCompany_AffiliationID = null;
task.SubjectID = null;
task.DoingDateTime = '1397/12/11';
task.MaturityDateTime = null;
task.ImportanceDegreeID = null;
task.StatusID = null;
task.CompletionPercentage = 0;
task.ReferenceFrom = 2;
task.ReferenceTo = 2;
task.DossierID = null;
var req = $.ajax({
url: 'http://localhost:3641/api/TaskApi',
contentType: 'application/x-www-form-urlencoded',
dataType: 'json',
data: task,
type: 'Post',
success: function (data) {
alert('success');
}
, error: function (response) {
alert(response.responseText);
}
});
我注意到的是由于信息发送到操作的方式导致的错误...
我在第一行action下了断点,但是程序没有进入action
感谢所有指导我的亲们
通过两件事解决了问题:
1- 模型中的必填字段之一未在 AJAX 中初始化
2-换句话说,数据值设置为JSON.stringify(任务)
我将网络 api 添加到可用的项目中。 我的 api 控制器:
namespace MyApplication.Controllers
{
public class TaskApiController : ApiController
{
[HttpPost]
public IHttpActionResult Create(string UserName, string Password, string DoingDateTime, int ReferenceFrom, int ReferenceTo, string MaturityDateTime = "", int? PersonCompany_AffiliationID = null, int? SubjectID = null, string Description = "", int? ImportanceDegreeID = null, int? StatusID = null, int CompletionPercentage = 0, int? DossierID = null)
{
...
return Ok();
}
}
}
WebApiConfig.cs:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
将以下代码添加到 web.config:
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept,Authorization" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>
</system.webServer>
和ajax:
$.ajax({
url: 'localhost:3641/api/TaskApi',
contentType: 'application/x-www-form-urlencoded',
dataType: 'json',
data: {
UserName: 'admin',
Password: '123',
Description: 'test',
DoingDateTime: '1397/12/10',
ReferenceFrom: 2,
ReferenceTo: 2
},
type: 'Post',
success: function (data) {
alert('success');
}
, error: function (response) {
alert(response.responseText);
}
});
当我在浏览器中测试 Web api 时:
它工作正常。但是当 aun ajax 它 return 错误和 response.responseText returns "undefined".
解决问题的最快捷、最简洁的方法是创建视图模型。
另外请记住,对于 复杂类型 Web Api 默认情况下使用媒体类型格式化程序从邮件正文中读取值。
public class TaskViewModel
{
public string UserName { get; set; }
public string Password { get; set; }
public string DoingDateTime { get; set; }
public int ReferenceFrom { get; set; }
public int ReferenceTo { get; set; }
public string MaturityDateTime { get; set; }
public int? PersonCompany_AffiliationID { get; set; }
public int? SubjectID { get; set; }
public string Description { get; set; }
public int? ImportanceDegreeID { get; set; }
public int? StatusID { get; set; }
public int CompletionPercentage { get; set; }
public int? DossierID { get; set; }
}
[HttpPost]
public IHttpActionResult Create(TaskViewModel taskViewModel)
{
if (!ModelState.IsValid)
{
return BadRequest("");
}
return Ok();
}
用你的class写了一个AJAX,还是失败了
var task = new Object();
task.Description = 'kjk';
task.PersonCompany_AffiliationID = null;
task.SubjectID = null;
task.DoingDateTime = '1397/12/11';
task.MaturityDateTime = null;
task.ImportanceDegreeID = null;
task.StatusID = null;
task.CompletionPercentage = 0;
task.ReferenceFrom = 2;
task.ReferenceTo = 2;
task.DossierID = null;
var req = $.ajax({
url: 'http://localhost:3641/api/TaskApi',
contentType: 'application/x-www-form-urlencoded',
dataType: 'json',
data: task,
type: 'Post',
success: function (data) {
alert('success');
}
, error: function (response) {
alert(response.responseText);
}
});
我注意到的是由于信息发送到操作的方式导致的错误... 我在第一行action下了断点,但是程序没有进入action
感谢所有指导我的亲们
通过两件事解决了问题: 1- 模型中的必填字段之一未在 AJAX 中初始化 2-换句话说,数据值设置为JSON.stringify(任务)