Calling WebApi from jQuery

心不动则不痛 提交于 2020-01-16 19:11:27

问题


Just started with WebApi and have multiple problems. Read tons of info, but probably missing some concepts.

In my controller:

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

First of all, no matter if I pass a parameter productName, the parameterless GetProduct is called (and should return data back) . I need to be able to call both of these GET methods. Second, the success function is not called. so I don't get any data back from WebApi methods.

Any tips or guidance is appreciated. Thanks. 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 }
        );
    }
}

Only problem right now is that I don't get my data alerted :

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

回答1:


Change either your method signature to

public Product GetProduct(string id)

Or your route to

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

The name of your method parameters determines the route selected.




回答2:


This is most probably due to same origin policy. Try moving your html file in visual studio solution (assuming you are using visual studio) and run it from there (e.g. localhost:62177/test.htm). If you receive results this way that would confirm the same origin policy blocking.




回答3:


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:

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



回答4:


partial answer - you have to set the data param in the jquery ajax call
and just for clarity -
you shouldnt probably use "data" as your return var
(i changed it to "result" below)
so:

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



回答5:


Try decorating ur web api method with

[HttpGet]

And parameter as

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

And then try



来源:https://stackoverflow.com/questions/15239782/calling-webapi-from-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!