首页 > 解决方案 > 在 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 时:

http://localhost:3641/api/TaskApi?UserName=admin&Password=312&Description=hkj&DoingDateTime=1397/02/05&ReferenceFrom=2&ReferenceTo=2

它工作正常。但是当aun ajax返回错误并且response.responseText返回“未定义”。

标签: ajaxasp.net-mvcasp.net-web-api2

解决方案


在你的课上,我写了一个 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);
            }
});

我注意到由于信息发送到操作的方式而导致的错误...我在操作的第一行放置了一个断点,但程序没有执行。


推荐阅读