【问题标题】:Calling WebApi from jQuery从 jQuery 调用 WebApi
【发布时间】:2013-02-20 19:08:16
【问题描述】:

刚开始使用 WebApi 并遇到多个问题。阅读大量信息,但可能缺少一些概念。

在我的控制器中:

    public IEnumerable<Product> GetProducts()
    {
        return db.Products.AsEnumerable();
    }


    public Product GetProduct(string name)
    {
        Product product = db.Products.FirstOrDefault(p => p.Name == name);
        if (product == null)
        {
            throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
        }

        return product;
    }

Javascript:

 $('#Search').click(function () {
    jQuery.support.cors = true;
    var productName = $('#Name').val();

    $.ajax({

        url: "http://localhost:62178/api/product",
        //url: "http://localhost:62178/api/product/" + productName,
        type: "GET",
        success: function (data) {
            alertData(data);
        }
    });
});

首先,无论我是否传递参数productName,都会调用无参数的GetProduct(并且应该返回数据)。 我需要能够调用这两种 GET 方法。 二是不调用success函数。所以我没有从 WebApi 方法中获取任何数据。

感谢任何提示或指导。谢谢。 WebApiConfig.cs

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

现在唯一的问题是我的数据没有收到警报:

$('#Search').click(function () {
    jQuery.support.cors = true;
    var productName = $('#Name').val();

    $.ajax({

        url: "http://localhost:62177/api/product/" + productName,
        //data: { name: productName },
        type: "GET",
        dataType: "jsonp",
        error: function (request, status, error) {
            alert(request.responseText);
        },
        success: function (data) {
            alert(data);
        }
    });
});

【问题讨论】:

  • dataType='' 不见了,你对 webapi 有什么期待 htmljsontextscript
  • 您检查过任何控制台错误吗?
  • 没有控制台错误,数据类型相同:“json”。
  • 您使用哪个版本的 jQuery?你有什么例外?
  • @Cuong Le, 1.7.1 也不例外。我添加了错误:function() { alert("error"); },到我的 $.ajax 并且它没有被提醒。

标签: jquery asp.net-mvc get asp.net-web-api


【解决方案1】:

将您的方法签名更改为

public Product GetProduct(string id)

或者你的路线

routeTemplate: "api/{controller}/{name}"

方法参数的名称决定了选择的路由。

【讨论】:

    【解决方案2】:

    这很可能是由于同源政策。尝试在 Visual Studio 解决方案中移动您的 html 文件(假设您使用的是 Visual Studio)并从那里运行它(例如 localhost:62177/test.htm)。如果您以这种方式收到结果,将确认同源策略阻止。

    【讨论】:

      【解决方案3】:

      首先,我假设您正在使用 Internet Explorer 查看您的网站,因为您在控制台中没有看到错误的事实恰好发生在我身上,但是如果您尝试使用 Chrome,您应该在控制台上看到与此类似的错误:

      XMLHttpRequest cannot load http://localhost:44271/api/routes/1. Origin http://localhost:27954 is not allowed by Access-Control-Allow-Origin. 
      

      如果您没有看到错误,您仍然可以在 Chrome 开发者工具的“网络”选项卡上查看网络调用的结果。它很可能没有可用的响应,它应该被标记为失败的请求(不是 200 状态),如下所示:

      如果您的 MVC 网站与 WebAPI 位于单独的项目中,则当您使用 Visual Studio 启动调试时,它们将部署到 IIS Express 中的不同应用程序 (URLS)。

      这意味着,由于CORS policy.,对您的 WebAPI 的调用将被禁止

      但是,您可以使用Brock Allen's CORS implementation for WebAPI 解决此问题,ASP.NET 团队最近宣布了will be integrated directly to WebAPI on the next release

      我今天刚刚创建了一个简单的 PoC,遇到了同样的问题,并成功地使用 Brock 的实现来修复它。步骤很简单:

      1. 您不必对 ApiController 进行任何更改。
      2. 您将 CorsConfig 类添加到 App_Start 文件夹
      3. 您将对该 CorsConfig 类的调用添加到注册 CORS 支持的静态方法中
      4. 就是这样,您应该不再收到错误消息。请注意,此 CORS 配置将允许对所有方法、所有请求和所有来源进行 CORS 调用。我只是将它用于我的 PoC。您可以使用库的流畅配置方法进行更多限制。

      CorsConfig.cs

      public static void RegisterCors(HttpConfiguration httpConfig)
      {
          WebApiCorsConfiguration corsConfig = new WebApiCorsConfiguration();
      
          // this adds the CorsMessageHandler to the HttpConfiguration’s
          // MessageHandlers collection
          corsConfig.RegisterGlobal(httpConfig);
      
          // this allow all CORS requests to the Products controller
          // from the http://foo.com origin.
          corsConfig.AllowAll();
      }
      

      全球.asax

      protected void Application_Start()
          {
              AreaRegistration.RegisterAllAreas();
              WebApiConfig.Register(GlobalConfiguration.Configuration);
              FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
              RouteConfig.RegisterRoutes(RouteTable.Routes);
      
              CorsConfig.RegisterCors(GlobalConfiguration.Configuration);
          }
      

      【讨论】:

      • 整个 CorsConfig.cs 长什么样?我的有问题...
      • WebApiCorsConfiguration could not be found 错误。是否有我必须下载的 DLL?
      【解决方案4】:

      部分答案 - 您必须在 jquery ajax 调用中设置数据参数
      只是为了清楚起见 -
      您可能不应该使用“数据”作为您的返回变量
      (我在下面将其更改为“结果”)
      所以:

      $.ajax({
          url: "http://localhost:62178/api/product",
          data: {name: productName},
          type: "GET",
          success: function (result) {
              alertData(result);
          }
      });
      

      【讨论】:

        【解决方案5】:

        尝试用

        装饰你的 web api 方法
        [HttpGet]
        

        参数为

        [HttpGet]
        public Product GetProduct([FromUri]string name)
        

        然后试试

        【讨论】:

          猜你喜欢
          • 2012-06-20
          • 1970-01-01
          • 2018-11-26
          • 1970-01-01
          • 2017-01-04
          • 2016-02-01
          • 2015-05-17
          • 2013-03-15
          • 1970-01-01
          相关资源
          最近更新 更多