0

刚开始使用 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);
        }
    });
});
4

5 回答 5

4

将您的方法签名更改为

public Product GetProduct(string id)

或者你的路线

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

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

于 2013-03-06T06:51:36.060 回答
0

First of all, I'm assuming you're viewing your website using Internet Explorer, because the fact that you don't see an error in the console just happened to me, but if you try it with Chrome, you should see an error similar to this one on the console:

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

If you don't see the error, you can still check the result of the network call on the Network tab of Chrome's developer tools. It most likely will not have a Response available and it should be marked as a failed request (not 200 status), like this:

enter image description here

If your MVC website is in a separate project than your WebAPI, when you launch debugging with Visual Studio, they will be deployed to different applications (URLS) in IIS Express.

What this means is that the call to your WebAPI would be prohibited due to the CORS policy.

However, you can work around this by using Brock Allen's CORS implementation for WebAPI, which the ASP.NET team recently announced will be integrated directly to WebAPI on the next release.

I just had to create a simple PoC today and had the same problem, and successfully used Brock's implementation to fix it. The steps are pretty simple:

  1. You don't have to make any changes to your ApiController.
  2. You add a CorsConfig class to the App_Start folder
  3. You add a call to that CorsConfig class, to the static method that registers CORS support
  4. That's it, you should no longer be getting an error. Note that this CORS configuration will allow CORS calls for all methods, all requests and all origins. I just used it for my PoC. You can be more restrictive using the library's fluent configuration methods.

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();
}

Global.asax

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

        CorsConfig.RegisterCors(GlobalConfiguration.Configuration);
    }
于 2013-04-26T16:48:09.330 回答
0

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

于 2013-03-13T00:53:01.967 回答
0

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

$.ajax({
    url: "http://localhost:62178/api/product",
    data: {name: productName},
    type: "GET",
    success: function (result) {
        alertData(result);
    }
});
于 2013-07-04T19:39:39.490 回答
-1

尝试用

[HttpGet]

参数为

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

然后尝试

于 2013-03-06T06:28:32.500 回答