在asp.net core mvc web應用程序的開發過程當中,如果需要在控制器內使用同名的action,則會出現如下圖所示的問題:
https://docs.microsoft.com/zh-cn/aspnet/core/mvc/controllers/routing?view=aspnetcore-5.0
代碼片段如下:
- ` //GET: /HelloWorld/Welcome
- public string Welcome()
- {
- return "這是HelloWorld控制器下的Welcome Action方法.....";
- }
- //帶參數的Action
- //GET: /HelloWorld/Welcome?name=xxxx&type=xxx
- public string Welcome(string name, int type)
- {
- //使用Http Verb謂詞特性路由模板配置解決請求Action不明確的問題
- //AmbiguousMatchException: The request matched multiple endpoints. Matches:
- //[Controller]/[ActionName]/[Parameters]
- //中文字符串需要編碼
- //type為可解析為int類型的數字字符串
- string str = HtmlEncoder.Default.Encode($"Hello {name}, Type is: {type}");
- return str;
- }`
只要在瀏覽器的url地址欄輸入"/helloworld/welcome"這個路由地址段時,asp.net core的路由解析中間件便拋出上圖所示的請求操作不明確的問題。
根據官方文檔的描述,可以在控制器內某一個同名的action方法上添加http verb attribute特性的方式(為此方法重新聲明一個路由url片段)來解決此問題。對helloworld控制器內,具有參數的"welcome"這個action添加httpgetattr
修改后的代碼如下:
- //帶參數的Action
- //GET: /HelloWorld/Welcome?name=xxxx&type=xxx
- [HttpGet(template:"{controller}/WelcomeP", Name = "WelcomeP")]
- public string Welcome(string name, int type)
- {
- string str = HtmlEncoder.Default.Encode($"Hello {name}, Type is: {type}");
- return str;
- }
請求url: get -> "/helloworld/welcome?name=xxxxx&type=0"
到此這篇關于asp.net core mvc解決控制器同名action請求不明確的問題的文章就介紹到這了,更多相關asp.net core mvc控制器內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://www.cnblogs.com/zhaozix-blog/archive/2021/03/02/zzx_aspnetcore_action01.html