ajax - 在 ASP.NET MVC 5 中使用 jquery AJAX 调用 Web API 出现错误
问题描述
我将 web 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({
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返回错误并且response.responseText返回“未定义”。
解决方案
在你的课上,我写了一个 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);
}
});
我注意到由于信息发送到操作的方式而导致的错误...我在操作的第一行放置了一个断点,但程序没有执行。
推荐阅读
- homestead - 管理页面的 Sulu CMS“403 Forbidden”
- excel - 尝试在 Delphi 中构建 Excel RTD 服务器
- go - 在 vagrant vbox 上安装 golang 1.10
- javascript - 如果不为空,则将多个数组合并在一起
- ios - IOS/Storboard:使用自动布局在一个 Storyboard 中复制和粘贴视图控制器是否安全
- wsdl - 如何调用另一个 BPEL 作为子流程
- ethereum - 如何在 Truffle 测试中调用成员函数?
- angular - Typescript 如何从嵌套对象获取器返回类函数引用
- spring - 使用 BeanPostProcessor 将 RequestResponseBodyMethodProcessor 替换为 CustomMethodProcessor
- php - 希望循环遍历一组变量,如果它们存在则显示它们,然后用逗号分隔它们