c# - 如何在具有相同参数的两个不同动作方法之间进行路由
问题描述
我正在开发带有属性路由的 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
但是在这两种情况下,第一个操作方法每次都会被调用。我如何在方法名称不同但参数具有相同名称和类型(或不同类型)的情况之间进行路由?
解决方案
您的路由定义与您的 URL 不匹配:
[Route("{getVersion}")]
这需要一个路由参数“getVersion”,因此即使是类似的 URL/api/settings/1
也会匹配。您应该重写它,使其不是参数:
[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)
推荐阅读
- math - OmniMarkupPreviewer 404 当我设置“mathjax_enabled”时:true
- c - C错误处理:如果错误返回int代码其他值?
- c# - C# String.Replace() & Regex.Replace() 在我的最后不起作用
- unit-testing - 如何模拟`std::fs::File`以便检查`File::set_len`是否在单元测试中正确使用?
- postgresql - 如何在多 goroutines 中运行 postgres Tx
- parsing - 单子的泛化是否可以接受?
- java - 如何在状态栏中显示没有图标的通知
- c# - 使用正确加载的列表对象时接收到 LINQ 表达式 x 无法翻译错误
- javascript - 我正在尝试将多个图像下载为 zip 文件,但不幸的是出现错误 Loading 'phpOWyJmt.png' failed Loading meta information failed
- python - 我想将特定列保存到python中的新excel表中