【问题标题】:Web API Ajax calling not workingWeb API Ajax 调用不起作用
【发布时间】:2014-05-01 10:32:05
【问题描述】:

这是我调用自定义 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.
        }
    });

这工作正常,但如果我使用“数据”标签发送数据,它就不起作用。如下所示。

 $.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
    }

使用提琴手第二个代码请求结果测试时出现 404 错误。直接从 URL 访问 Web API 方法工作正常。

答案::

在对这个主题进行 R'N'D 之后,我开始知道 Web API 参数绑定存在问题。所以,我们可以使用 [formUri] 标签或者我们可以有一个模型类。像这样

公共类 IndustryName { 公共字符串 Industryname { 获取;放; } }

在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

【问题讨论】:

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


    【解决方案1】:

    更改下一行

    data: { 'industryName': addNewIndustryName }
    

    到

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

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

    或者你可以像下面这样简单地分配不带花括号的变量

    data: 'industryName='+ addNewIndustryName
    

    【讨论】:

    • 控制台有错误吗? ...你可以为此分享 jsfiddle
    • 正如您在 ajax 中发送数据对象之前所说的那样,它工作正常,所以您能否检查一下 jquery ajax 调用是否可以访问 addNewIndustryName 对象
    • 是的,它可以访问...在 ajax 正文中,我使用了 firebug 和 alert msg 本身来确认。
    • 未找到与请求 URI 'localhost:XXXX/api/AdminAPI/IndustryPost' 匹配的 HTTP 资源。这是错误函数中显示的消息。
    • 看到这个帖子,可能对你有用stackoverflow.com/…我对asp .net不太了解:(
    【解决方案2】:

    在这里,您的 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.
        }
    });
    

    【讨论】:

    • 我的错,我匆忙发布了它。但在我的代码中它是正确的。
    • 好的!尝试使用此url: '/api/AdminAPI/IndustryPost/', 更改您的网址,最后添加/。
    猜你喜欢
    • 2018-05-08
    • 2019-01-15
    • 2014-01-01
    • 1970-01-01
    • 2017-02-26
    • 1970-01-01
    • 1970-01-01
    • 2015-03-12
    • 2016-07-14
    相关资源
    最近更新 更多