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

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

   本人最近在研究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就是不修复,还得我们自己百度找答案!

@陈卧龙的博客

解决webApi<Message>An error has occurred.</Message>不能写多个Get方法的问题的更多相关文章

  1. iis 7 -mvc WebApi {"message":"an error has occurred"}

    iis 7 - WebApi's {"message":"an error has occurred"} 原因是web api的Controller有两个类名重 ...

  2. Swagger发布服务器时错误 500 : { "Message": "An error has occurred." }

    在做Web API的文档自动生成时,本机调试都正常,发布到服务器上出现500错误 500 : { "Message": "An error has occurred.&q ...

  3. 解决MyEclipe出现An error has occurred,See error log for more details的错误

    今晚在卸载MyEclipse时出现An error has occurred,See error log for more details的错误,打开相应路径下的文件查看得如下: !SESSION 2 ...

  4. idhttp post 出现exception class EIdSocketError with message 'Socket Error # 10054的解决办法(捕捉异常,防止程序挂掉)

    由于项目需要.需要向一个地址提交数据.提交的次数很频繁,但是程序经常raised exception class EIdSocketError with message 'Socket Error # ...

  5. nova instance出错:"message": "Proxy error: 502 Read from server failed

    执行 $ nova resize instance1 时候出错: {, "details": " File \"/opt/stack/nova/nova/com ...

  6. eclipse启动出现“An Error has Occurred. See the log file”解决方法

    最近在启动eclipse时出现了“An Error has Occurred. See the log file”的错误,点击确定后也不能启动eclipse.查看log文件,出现类似: java.la ...

  7. [PHP][REDIS]phpredis 'RedisException' with message 'read error on connection'

    最近一个后台常驻job通过redis的brpop阻塞读取消息时,设置了永不超时 while( $re=$redis->brPop($queue_name,0) ){ } 但是在实际的使用中发现很 ...

  8. AndroidStudio3.0无法打开Android Device Monitor的解决办法(An error has occurred on Android Device Monitor)

    ---恢复内容开始--- 打开monitor时出现 An error has occurred. See the log file... ------------------------------- ...

  9. ERROR: Cannot load message class for [speech_control/command]. Are your messages built?

    ubuntu14.04 ROS indigo 问题: 执行查看指定消息的命令,出现下面的错误提示,找不到该消息类型. ~$ rostopic echo /speech/command ERROR: C ...

随机推荐

  1. js 获取checkbox选中项目

    # //获取选中项 $('#submit').click(function () { var check_list = [] $("input[name='ck']:checked" ...

  2. 一些浏览器的USER-AGENT

    115浏览器的USER-AGENT 版本号:5.1.3.55 Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like G ...

  3. jQuery之换肤与cookie插件

    有时候一个网页可以有多个皮肤进行选择,也就是不同的背景,或是一整套新的css,能使整个页面变成另一种风格. 这个功能可以用jQuery来实现.外加cookie插件.有了cookie,就可以长时间的保存 ...

  4. Decoder with 3 Inputs and 2 3 = 8 Outputs

    COMPUTER ORGANIZATION AND ARCHITECTURE DESIGNING FOR PERFORMANCE NINTH EDITION

  5. myeclipse调式与属性显示

    最近做项目的时候发现一个奇怪的东西,当我用myeclipse调式时,调式窗口显示实体user所关联的role的对象属性是空的,但是,从syst打印出来是有的,最近感到很奇怪,后来发现这只是调式的一种显 ...

  6. sqlserver 计算 百分比

    ,),))+'%' As 百分比 NUMERIC(P,S) P的默认值是:38 S的默认值是:-84~127 numeric(a,b)函数有两个参数,前面一个为总的位数,后面一个参数是小数点后的位数, ...

  7. VirtualBox 使用技巧

    一.VirtualBox 的快捷键 VirtualBox 默认的 Host 键是 Right Ctrl Host 键可以点击 Oracle VM VirtualBox 管理器的左上角 “管理”-> ...

  8. zepto源码--定义变量--学习笔记

    主要了解一下zepto定义的初始变量. 逐一以自己的理解解析,待到后面完全透彻理解之后,争取再写一遍zepto源码学习的文章. 其中的undefined确实不明白为什么定义这么个变量在这里. docu ...

  9. C# 中==与Equals方法比较

    先来段代码,如下: static void Main(string[] args) { string a = new string(new char[] { 'h', 'e', 'l', 'l', ' ...

  10. jQuery 遍历json数组的实现代码

    <script type="text/javascript"> "}]; $(d1).each(function(){ alert(this.text+&qu ...