获取方法冲突无法在Web API中解决

时间:2014-09-26 11:13:31

标签: asp.net asp.net-mvc rest asp.net-web-api

我的webapi获取MoviesController中的方法

// GET api/movies
        /// <summary>
        /// Returns the sorted list of movies
        /// </summary>
        /// <returns>Collection of Movies</returns>
        public IEnumerable<Movie> Get()
        {
            return repository.GetMovies().OrderBy(c => c.Title);
        }

        /// <summary>
        /// Returns an individual movie
        /// </summary>
        public Movie Get(int movieId)
        {
            var movie = repository.GetMovieById(movieId);
            if (movie == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
            return movie;
        }

和WebApiConfig.cs是

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 }
            );
        }

我面临的问题是每次Get()被调用。获取Id方法没有被调用。我已经尝试过在SO上给出的各种解决方案,但它对我不起作用。

1 个答案:

答案 0 :(得分:1)

再显示一条自定义路线

config.Routes.MapHttpRoute(
     name: "MyRoute",
     routeTemplate: "api/{controller}/{action}/{movieId}",
     defaults: new { movieId = "0" }  //instead of default movieid '0' you can specify as per your requirement.
   );