ASP.NET MVC 4:一次只允许一个请求

use*_*689 4 c# asp.net-mvc request controller-action sequential

在我的 ASP.NET MVC 应用程序中,我想按顺序处理所有请求;任何动作/控制器代码都不应与另一个同时执行。如果两个请求在相似的时间进入,它应该先运行第一个,然后在第一个完成后运行第二个。

除了使用全局锁变量之外,还有更好的方法吗?

编辑:该应用程序更像是 Web 上的批处理/服务,用于执行 Web 服务调用和清理数据库。站点中不同的 URL 导致不同的批处理操作。这不是面向最终用户的站点。因此,我需要这样做,以便一次只完成一个对 URL 的请求(将执行一些批处理操作),否则,如果批处理操作的代码与其自身或其他批处理操作同时运行,则可能会损坏批处理操作. 事实上,如果另一个请求在当前正在执行时出现,它根本不应该运行,即使在前一个请求完成之后;它应该只给出一个错误信息。

我想知道是否有办法在 IIS 而不是代码中做到这一点。如果我有一个全局锁变量,它会使代码更复杂,我可能会在死锁中运行,其中锁变量设置为 true 但永远不能设置为 false。

编辑:实施计划的示例代码

[HttpPost]
public ActionResult Batch1()
{
    //Config.Lock is a global static boolean variable
    if(Config.Lock) { Response.Write("Error: another batch process is running"); return View(); }
    Config.Lock = true; 

    //Run some batch calls and web services (this code cannot be interleaved with ExecuteBatchCode2() or itself)
    ExecuteBatchCode();

    Config.Lock = false;
    return View();
}

[HttpPost]
public ActionResult Batch2()
{
    if(Config.Lock) { Response.Write("Error: another batch process is running"); return View(); }
    Config.Lock = true;

    //Run some batch calls and web services (this code cannot be interleaved with ExecuteBatchCode1() or itself)
    ExecuteBatchCode2();

    Config.Lock = false;
    return View();
}
Run Code Online (Sandbox Code Playgroud)

我是否需要担心代码没有达到 Config.Lock = false 的情况,导致 Config.Lock = true 永远,导致不再提供更多请求?

Tig*_*ran 5

您已尽可能多地接受请求,人们不喜欢在浏览器前等待。但是之后,在服务端,你可以将它们推入(比如说)Queue<T>并按顺序处理它们。

简而言之:

  • 以异步方式接受
  • 在服务器上按顺序处理


spe*_*der 5

你可以写一个属性:

public class ExclusiveActionAttribute : ActionFilterAttribute
{
    private static int isExecuting = 0;
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (Interlocked.CompareExchange(ref isExecuting, 1, 0) == 0)
        {
            base.OnActionExecuting(filterContext);   
            return; 
        }
        filterContext.Result = 
            new HttpStatusCodeResult(HttpStatusCode.ServiceUnavailable);
    }

    public override void OnResultExecuted(ResultExecutedContext filterContext)
    {
        base.OnResultExecuted(filterContext);
        Interlocked.Exchange(ref isExecuting, 0);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在您想要控制的控制器/方法上使用它:

[ExclusiveAction] //either here, for every action in the controller
public class MyController : Controller
{
    [ExclusiveAction] //or here for specific methods
    public ActionResult DoTheThing()
    {
        //foo
        return SomeActionResult();
    }
}
Run Code Online (Sandbox Code Playgroud)