如果我有这个 Action :
public ActionResult MyAction(long? personId)
{
// ...
}
我可以使用以下 URL 调用该操作:
localhost/MyAction/?personId=x
我希望能够发送另一个额外参数(token
),该参数将出现在来自客户端的所有 ajax 调用中:
localhost/MyAction/?personId=x&token=asdf
无需在我的所有操作签名中声明这个新参数。那它:我想避免这种情况:
public ActionResult MyAction(long? personId, string token)
{
// ...
}
public ActionResult MyAction2(long? animalId, string token)
{
// ...
}
etc.
但我也希望能够从方法内部访问 token
参数。即:
public ActionResult MyAction(long? personId)
{
// I can check the token's value or manipulate it, eg:
if (token.Equals(...)) { .. }
}
问题:
有没有办法在我的所有(或部分)操作中隐式声明此参数?也许使用属性?
最佳答案
您可以从公共(public)基础 Controller 派生所有 Controller 。 然后,重写其中的 OnActionExecuting 并访问查询字符串。例如:
public class BaseController : Controller
{
protected string Token { get; private set; }
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
string token = Request.QueryString["token"] as string;
Token = token ?? string.Empty;
}
}
我发现这是比静态类更干净的解决方案。此外,BaseController 是 MVC 中一种有用的模式,可以共享许多 Controller 中使用的代码。
关于c# - 在 ASP.NET MVC 操作中隐式声明参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27367621/