Asp.net mvc 什么是ActionResult AcceptVerbsAttribute默认HTTP方法?
我知道您可以通过添加AcceptVerbsAttribute来限制特定ActionResult方法响应的HTTP方法,例如Asp.net mvc 什么是ActionResult AcceptVerbsAttribute默认HTTP方法?,asp.net-mvc,Asp.net Mvc,我知道您可以通过添加AcceptVerbsAttribute来限制特定ActionResult方法响应的HTTP方法,例如 [AcceptVerbs(HttpVerbs.Get)] public ActionResult Index() { ... } 但我想知道:如果没有显式的[AcceptVerbs(…)]属性,ActionResult方法会接受哪些HTTP方法 我想应该是获取、头部和发布,但只是想再次检查 谢谢。如果没有AcceptVerbsAttribute您的操作将接受任何H
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Index() {
...
}
但我想知道:如果没有显式的[AcceptVerbs(…)]属性,ActionResult方法会接受哪些HTTP方法
我想应该是获取、头部和发布,但只是想再次检查
谢谢。如果没有
AcceptVerbsAttribute
您的操作将接受任何HTTP方法的请求。顺便说一句,您可以在RouteTable中限制HTTP方法:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" }, // Parameter defaults
new { HttpMethod = new HttpMethodConstraint(
new[] { "GET", "POST" }) } // Only GET or POST
);
它将接受所有HTTP方法
查看ActionMethodSelector.cs中稍微格式化的片段(可以下载ASP.NET MVC源代码):
private static List RunSelectionFilters(ControllerContext
controllerContext,List methodInfos)
{
//删除选择退出此请求的所有方法
//若要选择退出,必须至少在方法上定义一个属性
//返回错误
List MatchesWithSelectionAttribute=new List();
List MATCHES WITHOUTHELECTIONATTRIBUTES=新列表();
foreach(MethodInfo中的MethodInfo MethodInfo)
{
ActionMethodSelectorAttribute[]属性=
(ActionMethodSelectorAttribute[])方法信息。
GetCustomAttributes(typeof(ActionMethodSelectorAttribute),
真/*继承*/);
如果(attrs.Length==0)
{
不带选择属性的匹配。添加(methodInfo);
}
其他的
如果(attrs.All)(attr=>attr.IsValidForRequest(controllerContext,
方法(信息)))
{
匹配SelectionAttribute.Add(methodInfo);
}
}
//如果匹配的操作方法具有选择属性,
/考虑它比匹配动作方法更具体
//没有选择属性
返回(与SelectionAttributes.Count匹配>0)?
与选择属性匹配:
不带选择属性的匹配;
}
因此,如果没有更好的匹配带有显式属性的操作方法,则将使用不带属性的操作方法。我的猜测是任意的(还包括PUT、DELETE)。我想你可以通过实验找到答案——做一个没有AcceptVerbs属性的简单测试动作,对它抛出一些不同的请求,看看会发生什么。我很想知道答案:-)我不知道你可以通过RouteTable限制HTTP方法-这正是我想要的。谢谢
private static List<MethodInfo> RunSelectionFilters(ControllerContext
controllerContext, List<MethodInfo> methodInfos)
{
// remove all methods which are opting out of this request
// to opt out, at least one attribute defined on the method must
// return false
List<MethodInfo> matchesWithSelectionAttributes = new List<MethodInfo>();
List<MethodInfo> matchesWithoutSelectionAttributes = new List<MethodInfo>();
foreach (MethodInfo methodInfo in methodInfos)
{
ActionMethodSelectorAttribute[] attrs =
(ActionMethodSelectorAttribute[])methodInfo.
GetCustomAttributes(typeof(ActionMethodSelectorAttribute),
true /* inherit */);
if (attrs.Length == 0)
{
matchesWithoutSelectionAttributes.Add(methodInfo);
}
else
if (attrs.All(attr => attr.IsValidForRequest(controllerContext,
methodInfo)))
{
matchesWithSelectionAttributes.Add(methodInfo);
}
}
// if a matching action method had a selection attribute,
// consider it more specific than a matching action method
// without a selection attribute
return (matchesWithSelectionAttributes.Count > 0) ?
matchesWithSelectionAttributes :
matchesWithoutSelectionAttributes;
}