【问题标题】:Web api 2 attribute routing not working even with it configured in WebApiConfig即使在 WebApiConfig 中配置了 Web api 2 属性路由也无法正常工作
【发布时间】:2018-01-30 07:55:04
【问题描述】:

我不明白为什么我的属性路由不起作用。如果我转到“http://localhost:56125/api/Contact/1682”,那么我会得到显示“value1”和“value2”的测试控制器,但如果我转到http://localhost:56125/api/contacts/1682,那么我会得到No HTTP resource was found that matches the request URI 'http://localhost:56125/api/contacts/1682',我不明白为什么?

在 ContactController.cs 中:

public class ContactController : ApiController
{
    private readonly NGSystemRepository _repo = new NGSystemRepository();

    // GET: api/Contact
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }


    [Route("api/contacts/{contactId}")]
    [HttpGet]
    public ContactInformation GetContactInformation(int contactNumber)
    {
        return _repo.GetContact(contactNumber);
    }
}

在 WebApiConfig 中:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
        // Configure Web API to use only bearer token authentication.
        config.SuppressDefaultHostAuthentication();
        config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

        // Web API routes
        config.MapHttpAttributeRoutes();

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

【问题讨论】:

    标签: asp.net-web-api routing asp.net-web-api2 attributerouting


    【解决方案1】:

    啊!愚蠢的错误。我没有将属性属性名称(contactId)与方法属性名称(contactNumber)匹配。

    我的控制器操作应该是:

    [Route("api/contacts/{contactId}")]
    [HttpGet]
    public ContactInformation GetContactInformation(int contactId)
    {
        return _repo.GetContact(contactNumber);
    }
    

    【讨论】:

      猜你喜欢
      • 2018-06-23
      • 2015-02-14
      • 2018-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      • 2020-05-02
      • 1970-01-01
      相关资源
      最近更新 更多