使用 Ajax 调用 Web Api 2 方法

Calling a Web Api 2 Method using Ajax

我有一个用于移动项目的 Web Api 2 项目。我正在尝试对 Web 项目使用相同的 api,但无法使用 ajax 访问它们。我已经确认我的 url 是正确的,并且我能够从 android 项目和提琴手到达终点。我错过了什么是我的 ajax 电话吗?我总是点击错误函数,returns '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);
                }
            });

contentType 是内容类型 sent 到服务器;这是我可以想象您的代码无法正常工作的唯一可能原因,因为您说它实际上从未发出请求,所以它必须是 jQuery 在发出请求之前完成的一些错误处理,并且抛出错误是因为您是尝试为 GET 请求指定 contentType

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

如果尝试从浏览器访问 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