使用Ajax调用Web Api 2方法

时间:2015-07-18 16:14:55

标签: javascript jquery ajax asp.net-web-api asp.net-web-api2

我有一个用于移动项目的Web Api 2项目。我正在尝试使用相同的api用于Web项目,但无法使用ajax访问它们。我已经确认我的网址是正确的,我可以从Android项目和fiddler中获取端点。我错过了什么是我的ajax电话?我总是点击错误功能,返回' undefined'。我可以在我的webapi项目中设置断点,并且该端点永远不会被击中。

// GET: api/Trips
public IQueryable<Trip> GetTrips()
{
     return db.Trips.Include("Users");
}

jquery的

            $.ajax({
                url: 'http://localhost:49669/api/Trips',
                type: 'GET',
                contentType: 'application/json;charset=utf-8',
                success: function (data) {
                    alert("success!!");

                },
                error: function (x, y) {
                    alert(x.response);
                }
            });

2 个答案:

答案 0 :(得分:2)

如果尝试通过浏览器访问您的API,则可能需要启用CORS。

步骤1,修改WebApiConfig文件(App_Start / WebApiConfig.cs):

using System.Web.Http;
namespace WebService
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Add this line
            config.EnableCors();

            // the rest of your code
        }
    }
}

步骤2,将[EnableCors]属性添加到Web API控制器:

using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Cors;

namespace MyApp.Controllers
{
    [EnableCors(origins: "http://www.whatever.net", headers: "*", methods: "*")]
    public class HelloWorldController : ApiController
    {
        // GET: api/Trips
        public IQueryable<Trip> GetTrips()
        {
          return db.Trips.Include("Users");
         }
    }
}

**注意:**您可能还需要安装CORS nuget包。

Install-Package Microsoft.AspNet.WebApi.Cors

答案 1 :(得分:0)

contentType用于将内容类型beint 发送到服务器;这是唯一可能的原因,我可以想象你的代码没有工作,因为你说它从来没有实际发出请求所以它必须是在发出请求之前由jQuery完成的一些错误处理,并且因为你是错误而被抛出尝试为contentType请求指定GET

指定响应类型的属性为dataType。尝试将contentType更改为dataType