[英]How to route between two different action methods with same parameters
我正在使用屬性路由開發ASP.NET Web API 2。 我有一個控制器類和兩個操作方法:
[RoutePrefix("api/settings")]
public class SettingsController : ApiController
{
[Route("{getVersion}")]
public async Task<IHttpActionResult> GetDBVersion(string PlatformID)
{
try
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
SqlManager sqlManager = new SqlManager();
DataTable dt = sqlManager.GetLocalDBVersion(PlatformID);
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
foreach (DataRow dr in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
return Ok(serializer.Serialize(rows));
}
catch (Exception ex)
{
return Content(HttpStatusCode.ExpectationFailed, ex.Message);
}
}
[Route("getBookingSetting/{PlatformID:int}")]
public async Task<IHttpActionResult> GetDBBookingSetting(int PlatformID)
{
try
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
SqlManager sqlManager = new SqlManager();
DataTable dt = sqlManager.GetBookingSetting(PlatformID.ToString());
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
foreach (DataRow dr in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
return Ok(serializer.Serialize(rows));
}
catch (Exception ex)
{
return Content(HttpStatusCode.ExpectationFailed, ex.Message);
}
}
我正在通過url調用第一個操作方法:
/api/settings/getVersion?PlatformID=1
第二個是:
/api/settings/getBookingSetting?PlatformID=1
但是,在兩種情況下,第一個操作方法都會被調用。 在方法名稱不同但參數具有相同名稱和類型(或不同類型)的情況下,如何進行路由?
您的路線定義與您的網址不匹配:
[Route("{getVersion}")]
這需要一個路由參數“ getVersion”,因此即使是/api/settings/1
類的URL也將匹配。 您應該重寫它,使其不是參數:
[Route("getVersion")]
public async Task<IHttpActionResult> GetDBVersion([FromUri]string PlatformID)
下一個:
[Route("getBookingSetting/{PlatformID:int}")]
此定義期望PlatformID
作為路由的一部分(即/api/settings/getBookingSetting/1
),但是您將其作為查詢字符串傳遞。
您應該將定義更改為此:
[Route("getBookingSetting")]
public async Task<IHttpActionResult> GetDBBookingSetting([FromUri]int PlatformID)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.