【问题标题】:Asp.Net WebAPI and AttributeRouting - no overloaded attribute constructor?Asp.Net WebAPI 和 AttributeRouting - 没有重载的属性构造函数?
【发布时间】:2013-05-03 12:53:16
【问题描述】:

我刚刚下载了用于 WebAPI 的 AttributeRouting NuGet 包,但我的控制器出现了问题。 我认为使用它的方法是:

 public class InboxController : ApiController
    {
        private IInboxService _inboxService;

        public InboxController(IInboxService inboxService)
        {
            _inboxService = inboxService;            
        }

        public IEnumerable<MessageModel> GetAll()
        {
            return _inboxService.GetAllMessages();
        }

      [HttpGet("Inbox/Count")]
            public int GetInboxCount()
            {
                return _inboxService.GetMessageCount();
            }
}

但是我收到以下错误: 错误 2 'System.Web.Http.HttpGetAttribute' 不包含采用 1 个参数的构造函数

我需要尽快启动并运行它。 HttpGet 属性没有重载的构造函数有什么原因吗?

更新

    [GET("Inbox/EnquiryCount")]
    public EnquiryCountModel GetEnquiryCounts()
    {
        var model = new EnquiryCountModel();
        model.EnquiryCount = _inboxService.GetCustomerEnquiriesCount();
        model.EnquiryResponseCount = _inboxService.GetCustomerEnquiryResponseCount();
        return model;
    }

在路线中:

routes.MapHttpRoute("InboxEnquiryApi", "api/inbox/{action}", new { Controller = "Inbox" }, null, new WebApiAuthenticationHandler(GlobalConfiguration.Configuration));

当我点击 'api/inbox/EnquiryCount' 的 URL 时,我收到此错误:

**No HTTP resource was found that matches the request URI 'http://localhost:49597/api/inbox/enquirycount'**

【问题讨论】:

  • 它是 GETAttribute 而不是 HttpGet
  • GetAttribute 编译时没有解析,你确定吗?
  • 是的,GETAttribute。添加使用 AttributeRouting.Web.Http;
  • GET 当然可以;)但是现在我发现了多个与请求错误匹配的多个操作。我认为这就是这个图书馆的全部意义所在。不能混用吗?
  • 您需要了解 ASP.NET Web API 路由在内部是如何工作的。它使用 url 作为资源。 AttributeRouting 只是添加一个路由,类似于 global.asax 路由。它不能改变底层引擎。 asp.net/web-api/overview/web-api-routing-and-actions

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


【解决方案1】:
【解决方案2】:

此语法在较新版本的 webapi 中已更改。 [HTTPPOST] 现在是独立的,并且路由的新属性恰当地命名为 ROUTE,它采用路由 url 例如。

[Route("GetRes/{month}")]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-17
    相关资源
    最近更新 更多