无法解决使用路径'Entry'和方法'GET'使用属性路由的多个操作



我正在托管我自己的WebApi,如下所示: 这是作为Windows服务运行的,因此可以启动和停止。

我正在使用Swagger/Swashbuckle来测试我的api。

我有以下代码。

public class ApiShell : IApiShell
    {
        IDisposable _webApp;
        public void Start()
        {
            _webApp = WebApp.Start<Startup>("http://localhost:9090");
            Console.WriteLine($"Web server running at 'http://localhost:9090'");
        }
        public void Stop()
        {
            _webApp.Dispose();
        }
        internal class Startup
        {
            //Configure Web API for Self-Host
            public void Configuration(IAppBuilder app)
            {
                var config = new HttpConfiguration();
                config.EnableSwagger(c =>
                {
                    c.SingleApiVersion("1", "Api");
                    c.PrettyPrint();
                }).EnableSwaggerUi(c => c.EnableDiscoveryUrlSelector());
                var resolver = new AutofacWebApiDependencyResolver(IoC.Container);
                config.DependencyResolver = resolver;
                config.Routes.MapHttpRoute("DefaultApi", "{controller}/{id}", new { id = RouteParameter.Optional });
                config.MapHttpAttributeRoutes(); //Swagger does not load when I have the following uncommented
                config.Formatters.Remove(config.Formatters.XmlFormatter);
                app.UseWebApi(config);
                GlobalConfiguration.Configuration.EnsureInitialized();
            }
        }
    }

问题是,当我不添加config.MapHttpAttributeroutes时,我得到以下错误:

使用路径"Entry"和方法"GET"的多个操作

当我添加config.MapHttpAttributeRoutes来尝试解决此问题时,出现以下错误:

对象尚未初始化。确保在应用程序的启动代码中,在所有其他初始化代码之后调用 HttpConfiguration.EnsureInitialized((

我已经添加了GlobalConfiguration.Configuration.EnsureInitialized();,但这无济于事。

这是我的路线:

[RoutePrefix("api")]
    public class EntryController : ApiController
    {
        private IActorSystemShell _actorSystem;
        public EntryController(IActorSystemShell actorSystem)
        {
            _actorSystem = actorSystem;
        }
        [HttpPost]
        public async Task<dynamic> AddPhoneBook([FromBody] Entry entry)
        {
            ...
        }
        [HttpGet]
        public async Task<dynamic> GetEntries()
        {
            ...
        }
        [HttpGet]
        [Route("id/{id}")]
        public async Task<dynamic> GetEntryById(int id)
        {
            ...
        }
        [HttpGet]
        [Route("text/{searchText}/SearchAll")]
        public async Task<dynamic> SearchEntries(string searchText)
        {
            ...
        }
        [HttpGet]
        [Route("book/{bookId}/{searchText}")]
        public async Task<dynamic> SearchInPhoneBook(int bookId, string searchText)
        {
            ...
        }
    }

这可能是由于 Swagger 限制,如此处和此处所述。您可以尝试为所有 HttpGet 调用指定一个特定名称:

[SwaggerOperation("GETOPERATION"(]

这也可能是因为并非所有操作都具有路由属性

最新更新