c# - Web API 2 RoutePrefix 不起作用

标签 c# asp.net-web-api2 asp.net-web-api-routing

在 Controller 级别定义 RoutePrefix 时,当我尝试使用前缀为 http://localhost:55020/api/v2/dummy/get 的 URL 访问 API 类时,它会抛出 404。不过,这个 http://localhost:55020/api/dummy/get 工作得很好。

这是定义了 RoutePrefix 的 Controller 类

    [RoutePrefix("v2/dummy")]
    public class DummyController : ApiController
    {
        // GET api/values
        [SwaggerOperation("Get")]
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2", "value3" };
        }
    }

这是WebApiConfig

 public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }

最佳答案

改用属性路由

public class DummyController : ApiController
{
    // GET api/values
    [HttpGet]
    [Route("api/v2/dummy/get")]
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2", "value3" };
    }
}

如果你想要路由前缀那么

[RoutePrefix("api/v2/dummy")]
public class DummyController : ApiController
{
    // GET api/v2/dummy
    [HttpGet]
    [Route("get")]
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2", "value3" };
    }
}

关于c# - Web API 2 RoutePrefix 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40081464/

相关文章:

c# - COM 方法调用在 C#、VB.NET 中失败,但在 Python 中有效

c# - Windows 7 任务栏中的跑马灯进度条

c# - 使用 MSMQ 和 SQL Server 的分布式事务,但有时会出现脏读

concurrency - 如何在 WebApi 操作中锁定长异步调用?

c# - OData v4 路由前缀?

c# - 无法在 MVC 项目中访问 Web API 2 Controller

c# - DataItem=null on binding,找不到原因?

Azure Web 服务 - 在运行时更改数据库连接字符串

c# - 如何在 webapi Controller 中反序列化来自 json 的参数

c# - Web Api HTTPPost 不接受 int