我想更好地了解 Controller 方法如何知道何时应该从发布数据或 url 中检索它接收的参数。
举个例子:
URL: /ModelController/Method/itemID
// Where itemID is the id (int) of the item in the database
POST: objectOrArray: {JSON Object/Array}
Controller 看起来像这样:
[HttpPost]
public ActionResult InputResources(int? id, Object objectOrArray)
现在,该方法以某种方式足够智能,可以查找第一个参数,id
。 , 在站点 URL 和 Object
在HTTPPost
.
虽然这行得通,但我不知道为什么,结果我有时会遇到不可预测和不稳定的行为。例如,我似乎发现(尽管我不是 100% 确定)删除 ?
来自 int? id
使 Controller 方法立即假设它应该在 HTTPPost
中查找 id而不是网址。
所以我想澄清以下几点:
到底是什么告诉方法去哪里寻找数据? (预示方法的 [HttpPost]
属性?)
命名约定是否起作用? (例如删除 ?
或不使用 id
作为变量名?)
变量的放置顺序是否有影响? (即将 Object
放在 id
之前)
我知道我可以或多或少地通过反复试验弄清楚其中的一些东西,但我想要一个合格的解释,而不是继续基于观察的假设工作。
谢谢
乔波
最佳答案
查看 Global.asax
中的默认路由:
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
MVC 将尝试做的第一件事是将您的方法参数映射到 POST 中的值。如果找不到匹配项,它将通过其他可能性级联,包括路由值。
这是模型 Binder 使用的顺序:
- Previously bound action parameters, when the action is a child action
- Form fields (Request.Form)
- The property values in the JSON Request body (Request.InputStream), but only when the request is an AJAX request
- Route data (RouteData.Values)
- Querystring parameters (Request.QueryString)
- Posted files (Request.Files)
您看到您描述的行为的原因是因为 POST 数据出现在路由值之前。似乎 MVC 无法将可为空的 int 绑定(bind)到 POST 值,因此它跳过它并继续前进,直到它到达 RouteData
映射,此时它找到匹配项并获取值从路线。当您使参数不可为 null 时,它突然能够将其绑定(bind)到 POST 值,它比 RouteData
具有更高的优先级,所以它确实如此。
关于c# - ASP.NET MVC : How does a controller distingush between parameters in the URL and sent by POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16232736/