WebAPI通过传递参数在控制器上找不到任何操作

时间:2016-09-28 07:46:15

标签: c# asp.net-web-api

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'."

3 个答案:

答案 0 :(得分:2)

这里的问题很简单。 您班级的访问修饰符非常严格

 class HomeController : ApiController
    {

默认访问修饰符是内部的,这意味着它不可公开访问。

尝试将访问修饰符更改为public以公开公开服务。

public class HomeController : ApiController
        {

我可以使用邮递员和现有的网络API复制您的问题。

My API Controller

邮差错误: enter image description here

答案 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);
}