繁体   English   中英

ASP.NET MVC 4-仅调用一种POST方法的Web API不会被调用

[英]ASP.NET MVC 4 - Web API with only one POST method does not get called

我正在做一个Web API,它可以对数据库执行任意SQL(从用户端通过Ajax传递,因此当然只有SELECT),并以JSON格式返回查询结果。

假设我已将此控制器命名为myQueryController,并将其定义为:

public class myQueryController : ApiController
{
    [HttpPost]
    public string Query(string sql)
    {
        string blll = sql;
        return blll;
    }
}

我的WebApiConfig.cs如:

// other routes

// the new route I added, well, in that my predecessor didn't follow the RESTful convention
config.Routes.MapHttpRoute(
    name: "myQuery",
    routeTemplate: "api/myquery/{action}/{id}",
    defaults: new
        {
            id = RouteParameter.Optional,
            action = "Query",
            controller = "myQuery",
        }
);

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

我通过Firefox中的Ajax发布到myQuery:

$.ajax(
    {
        type: "POST",
        url: "/api/myquery/query/",
        contentType: "application/json;charset=utf-8",
        success: function (results) {
            console.log(results);
        }
    }
);

但我收到404错误:

"NetworkError: 404 Not Found - http://localhost:5758/api/myquery/query/"

当我在Fiddler中编写POST请求时,出现了相同的404错误。

如果我在WebApiConfig.cs中删除了新的路由定义,则仍然会出现相同的错误。

感谢您的任何帮助,在此先感谢。

如果在我的情况下POST方法需要基本类型值(例如字符串类型),则必须在参数前加上“ [FromBody]”:

[HttpPost]
public string Query([FromBody]string sql)
{
    string myLocal = sql;
    return myLocal;
}

并将字符串传递给查询方法,您的Ajax将像这样:

$.ajax({
    url : "/api/myquery/query",
    data : "=select * from table",
    dataType : "text",
    type : "POST",
    success : function(res){ console.log(res); },
    error : function(req, stat, err){ console.log(stat + ": " + err); }
});

我从这篇文章中找到了解决方案: 如果方法参数为string或int则ASP.NET WebAPI抛出404 ,但是我发现字符串'hello world'周围的单引号不是必需的,您可以在第三个答案中找到它。

数据:“ ='hello world'”,

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM