在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"



轉載請註明出處,本文鏈接:https://www.uj5u.com/net/265244.html
標籤:.NET技术
