我有一个问题。
WebApiConfig
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}",
defaults: new
{
id = RouteParameter.Optional,
api = "api",
namespaces = new string[] { "able.application.api" }
}
);
}
}
Global.asax中
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
RouteConfig.RegisterRoutes(RouteTable.Routes);
GlobalConfiguration.Configuration.EnsureInitialized();
}
控制器
public class ContentModelController : ApiController
{
public ContentModelController()
{
}
[HttpPost, HttpGet]
public HttpResponseMessage Get(int? id)
{
return null;
}
}
问题是:当我调用get方法时,我收到以下错误。
CallUrl:http://localhost:54531/api/ContentModel/get?id=1
请帮帮我.. :(
<Error> <Message> No HTTP resource was found that matches the request URI 'http://localhost:54531/api/ContentModel/get?id=1'. </Message> <MessageDetail> No type was found that matches the controller named 'ContentModel'. </MessageDetail> </Error>
答案 0 :(得分:1)
使用此模板
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { action = "all", id = RouteParameter.Optional }
);
而不是
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}",
defaults: new
{
id = RouteParameter.Optional,
api = "api",
namespaces = new string[] { "able.application.api" }
}
);
在WebApiConfig.cs
文件中。
希望这对你有用。
答案 1 :(得分:1)
尝试按照Saurabh Srivastava的建议并将您的API调用更新为:
http://localhost:54531/api/ContentModel/get/1
或者您可以使用原始调用更新Get to the following方法签名:
public HttpResponseMessage Get([FromUri]int? id)