【发布时间】:2013-06-01 00:45:28
【问题描述】:
我是一名 WCF 开发人员,是 MVC 的新手。尝试将我的 WCF API 作为 ApiControllers 集成到 MVC 应用程序中(是否值得努力仍然是个大问题)。
我有一个来自 jQuery 插件的请求:
POST http://localhost:18698/Api/Public/DoAction HTTP/1.1
....
Content-Type: application/json; charset=UTF-8 Accept:
application/json, text/javascript, */*; q=0.01
{"myParam":"test"}
我的控制器如下所示:
public class PublicController : ApiController
{
[HttpPost]
public string DoAction(string myParam)
{
return "Test";
}
}
而且,路由部分如下所示:
config.Routes.MapHttpRoute(
name: "PublicApi",
routeTemplate: "api/{controller}/{action}"
);
我收到此错误:
{
"Message": "No HTTP resource was found that matches the request URI 'http://localhost:18698/Api/Public/DoAction'.",
"MessageDetail": "No action was found on the controller 'Public' that matches the request."
}
不接受任何 JSON 参数的方法工作正常,但接受 JSON 参数的方法不工作。我必须能够将复杂的 JSON 传递给方法。在 WCF 中,从 JSON 到对象的转换由 WCF 为我处理。
你知道我为什么会收到这个错误吗?我能否像在 WCF 中一样在 MVC 中无缝地传递/接收复杂的 JSON?
【问题讨论】:
-
以
application/x-www-form-urlencoded格式发布是否有效? (只是想排除您的 JSON 无效的可能性) -
我将 myParam=test 发布为 Content-Type: application/x-www-form-urlencoded;字符集=UTF-8。结果相同——在控制器上没有找到任何操作
-
您的路线似乎没问题,尝试将
DoAction更改为Post并删除[HttpPost]属性,动词类型隐含在ApiController中的动作名称中。跨度>
标签: json asp.net-web-api