HomeController.cs
class HomeController : ApiController
{
[HttpGet]
public IHttpActionResult GetData(string name)
{
if (string.IsNullOrWhiteSpace(name))
{
throw new ArgumentNullException("username can not be empty");
}
return Ok("Test Done");
}
}
StartUp.cs
public void Configuration(IAppBuilder appBuilder)
{
HttpConfiguration config = new HttpConfiguration();
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "GetData",
routeTemplate: "V2/{controller}/{name}",
defaults: new { controller = "Home", action = "GetData" }
);
appBuilder.UseWebApi(config);
}
获取错误:
{
"Message": "No HTTP resource was found that matches the request URI 'http://localhost:4057/V2/Home/GetData/'.",
"MessageDetail": "No type was found that matches the controller named 'Home'."
答案 0 :(得分:2)
这里的问题很简单。 您班级的访问修饰符非常严格
class HomeController : ApiController
{
默认访问修饰符是内部的,这意味着它不可公开访问。
尝试将访问修饰符更改为public
以公开公开服务。
public class HomeController : ApiController
{
我可以使用邮递员和现有的网络API复制您的问题。
答案 1 :(得分:0)
尝试将方法名称更改为Get
(更多关于http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api)。
如果您不想更改方法名称(http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2),也可以设置属性路由。
答案 2 :(得分:0)
作为Sherlock mentioned,API控制器必须是公开的。但是,考虑使用属性路由优于约定路由,因为它更不容易出错:
<强> HomeController.cs:强>
[RoutePrefix("V2/Home")]
public class HomeController : ApiController
{
[HttpGet]
[Route("{name}", Name = "GetData")]
public IHttpActionResult GetData(string name)
{
if (string.IsNullOrWhiteSpace(name))
{
throw new ArgumentNullException("username can not be empty");
}
return Ok("Test Done");
}
}
<强> Startup.cs:强>
public void Configuration(IAppBuilder appBuilder)
{
HttpConfiguration config = new HttpConfiguration();
config.MapHttpAttributeRoutes();
appBuilder.UseWebApi(config);
}