解决webApiAn error has occurred.不能写多个Get方法的问题

   最近悟出来一个道理,在这儿分享给大家:学历代表你的过去,能力代表你的现在,学习代表你的将来。

   十年河东十年河西,莫欺少年穷。 

   本人最近在研究C#webAPI相关知识,发现webAPI不能够支持多个Get方法,这些Get方法有如下一特点:

   相同数量的参数,这些参数类型可以不相同。奇怪的是:即使这些方法的返回值不同,方法名不同,但在程序请求执行过程中会出现如下错误提示:

<Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>
Multiple actions were found that match the request: System.Net.Http.HttpResponseMessage GetById(Int32) on type WebApiTest.Controllers.PersonController System.String GetBySex(System.String) on type WebApiTest.Controllers.PersonController
</ExceptionMessage>
<ExceptionType>System.InvalidOperationException</ExceptionType>
<StackTrace>
at System.Web.Http.Controllers.ApiControllerActionSelector.ActionSelectorCacheItem.SelectAction(HttpControllerContext controllerContext) at System.Web.Http.Controllers.ApiControllerActionSelector.SelectAction(HttpControllerContext controllerContext) at System.Web.Http.ApiController.ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancellationToken) at System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsyncInternal(HttpRequestMessage request, CancellationToken cancellationToken) at System.Web.Http.Dispatcher.HttpControllerDispatcher.SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
</StackTrace>
</Error>

   譬如:如下两个方法:

[HttpGet]
        public HttpResponseMessage GetById(int Id)
        {
            list = list.Where(p => p.Id == Id).ToList();
            return ResultToJson.toJson(list);
        }

        [HttpGet]
        public HttpResponseMessage GetByName([FromUri]string Name)
        {
            list = list.Where(p => p.Name == Name).ToList();
            return ResultToJson.toJson(list);
        }

   在请求过程中就会报上述错误,究其原因,是因为我们在Get请求时,两个方法都需要接收一个参数,导致了:不知道应该执行哪个方法的问题。

   你可能会问:我写的方法名不一样,并且在Get请求时,明确了请求的是哪个方法,为什么还会报错?

   究其原因,是因为WebApiConfig的配置引起的,在你新建的项目中,webApiConfig的配置是不指向Action的,初始的webApiConfig如下:

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

    routeTemplate: "api/{controller}/{id}",从这句可以看出,和Action没有任何毛关系,所以,GEt请求时:即使你指定了方法名,也会报错。

    因此:我们有必要修改下这个配置,修改成指向特定的Action,也就解决了上述问题。修改后的代码如下:

 public static void Register(HttpConfiguration config)
        {
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
               routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = RouteParameter.Optional }
            );
        }

   所以嘛,我认为VS项目初始化脑残,故意给我们程序员找麻烦,明知道潜在的问题,TMD就是不修复,还得我们自己百度找答案!

   @陈卧龙的博客

   

上一篇:科学构建大数据平台助力体育健身事业


下一篇:《黑客大曝光:移动应用安全揭秘及防护措施》一第1章 移动风险