Web API Ajax调用无法正常工作

时间:2014-03-24 07:15:19

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

这是我调用自定义web api方法的js代码..

$.ajax({
        url: '/api/AdminAPI/IndustryPost/?industryName='+addNewIndustryName,
        type: 'Post',
        cache: false,
        contentType: 'application/json; charset=utf-8',       
        success: function (response) {
           // response code.
        }
    });

这工作正常,但如果我使用'data'标签发送数据,它无法正常工作。喜欢以下。

 $.ajax({
        url: '/api/AdminAPI/IndustryPost',
        type: 'Post',
        cache: false,
        contentType: 'application/json; charset=utf-8',
        data: { 'industryName': addNewIndustryName },
        success: function (response) {
           // response code.
        }
    });

WebApiConfig是config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
             name: "DefaultApi",
             routeTemplate: "api/{controller}/{action}/{id}",
             defaults: new { id = RouteParameter.Optional }
        );

这是我的api方法

    [ActionName("IndustryPost")]
    public void AddIndustry(string industryName)
    {
        //code here
    }

用fiddler测试第二个代码请求结果为404错误。直接从URL访问Web API方法工作正常。

答案::

在对此主题做R'N'D后,我发现Web API参数绑定存在问题。那么,我们可以使用[formUri]标签或者我们可以拥有一个模型类。像这样

公共类IndustryName     {         public string Industryname {get;组; }     }

和web api方法

public void IndustryPost(IndustryName industryName)         {             //         }

jquery不需要更改。

这篇文章解释了这一切 Post int as part of method but get No HTTP resource was found that matches the request URI error

2 个答案:

答案 0 :(得分:0)

更改行

data: { 'industryName': addNewIndustryName }

data: '{ industryName:'+ addNewIndustryName +'}'

并确保addNewIndustryName是全局变量且可访问。

或者您可以简单地指定变量而不使用下面的花括号

data: 'industryName='+ addNewIndustryName

答案 1 :(得分:0)

这里你缺少ajax网址中的引用:

$.ajax({
    url: '/api/AdminAPI/IndustryPost/', //<----here put a / slash at the end
    type: 'Post',
    cache: false,
    dataType: 'json', //<-------you can use json
    contentType: 'application/json; charset=utf-8',
    data: { 'industryName': addNewIndustryName },
    success: function (response) {
       // response code.
    }
});