c# - 在 ASP.NET MVC 操作中隐式声明参数

标签 c# asp.net-mvc

如果我有这个 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/

相关文章:

c# - 在 Mono : invalid conversion of function? 中将 C++ 公开给 C#

asp.net-mvc - 编辑 View 时运行 MVC 项目的问题

c# - Task.Run 的替代方案

c# - 调用时无法将 lambda 表达式转换为类型 'System.Delegate'

c# - 单个线程上的线程 WaitHandle

c# - 如何在 C# 中使用表示反射结果类型的变量进行转换 .Invoke()

C#:如何在排序后选择 ListView 中的顶部项目

asp.net-mvc - 带有 JsonResult : ModelState is always valid 的 ASP.NET MVC 3

javascript - 进度条问题

asp.net-mvc - 在项目目录中指定要使用的项目文件