Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/339.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# Webapi函数不带参数,使用HttpGet可在404中获得结果_C#_Asp.net Web Api_Asp.net Web Api Routing_Attributerouting - Fatal编程技术网

C# Webapi函数不带参数,使用HttpGet可在404中获得结果

C# Webapi函数不带参数,使用HttpGet可在404中获得结果,c#,asp.net-web-api,asp.net-web-api-routing,attributerouting,C#,Asp.net Web Api,Asp.net Web Api Routing,Attributerouting,使用HttpGet且没有参数的webapi函数似乎无法添加路由。使用此代码 using System.Web.Http; namespace Testing { public class FooController: ApiController { [HttpGet] [Route("foobar")] public FoobarOutput foobar() { return new FoobarOutput();

使用
HttpGet
且没有参数的webapi函数似乎无法添加路由。使用此代码

using System.Web.Http;

namespace Testing
{
  public class FooController: ApiController
  {
    [HttpGet]
    [Route("foobar")]
    public FoobarOutput foobar()
    {
      return new FoobarOutput();
    }

    public class FoobarOutput
    {
      public int age;
      public string name;
    }
  }
}
浏览
/foobar
会导致404(找不到网页)

但是,如果我添加一个int参数

using System.Web.Http;

namespace Testing
{
  public class FooController: ApiController
  {
    [HttpGet]
    [Route("foobar/{id}")]
    public FoobarOutput foobar(int id)
    {
      return new FoobarOutput();
    }

    public class FoobarOutput
    {
      public int age;
      public string name;
    }
  }
}
我将能够冲浪到
/foobar/34
(任何整数都可以)

为什么我必须添加一个参数

(类
FoobarOutput
用于收集函数的输出值)

编辑
我已经成功地调用了一个无参数函数,所以现在我需要首先检查它为什么不工作。如果找不到,我将删除此问题。

请确保已启用属性路由

public static class WebApiConfig {
    public static void Register(HttpConfiguration config) {
        // Attribute routing.
        config.MapHttpAttributeRoutes();

        // Convention-based routing.
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}
并且控制器上存在适当的属性

[RoutePrefix("foobar")]
public class FooController: ApiController {

    //GET foobar
    [HttpGet]
    [Route("")]
    public IHttpActionResult foobar() {
        FoobarOutput model = new FoobarOutput();
        //...
        return Ok(model);
    }

    //GET foobar/34
    [HttpGet]
    [Route("{id:int}")]
    public IHttpActionResult foobar(int id) {
        FoobarOutput model = new FoobarOutput();
        //...
        return Ok(model);
    }

}
您的原始代码很可能使用默认的基于约定的路由


参考

显示控制器定义以及使用的任何属性。是否确实启用了属性路由?问题已被编辑。是的,我启用了属性路由,否则路由
/foobar/34
将未知。我远离“基于约定的路由”。我尝试像您一样使用RoutePrefix和Route,并且它工作正常(即使没有参数)。然后我尝试删除RoutePrefix并将路由放入route,这也起到了作用。所以我的问题被反驳了,我需要检查什么是不同的。另外,
[Route({id}”)]
应该足够了?仔细阅读路由约束。这就是我问题的答案吗?