I've implemented a throttling mechanism on my Login-action following this post. It works the way I want it to, except one thing. Whenever the mechanism is returning my message, I get redirected to a new, blank view with my message in it.
Is it possible, and if so how, to return this message back to my login-controller / view so it can be displayed in my _LoginPage.cshtml?
Here's my attribute:
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class ThrottleAttribute : ActionFilterAttribute
{
public string Name { get; set; }
public int Seconds { get; set; }
public string Message { get; set; }
public int AllowedRetries { get; set; }
private int _loginAttempts = 1;
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
string key = string.Concat(Name, "-", filterContext.HttpContext.Request.UserHostAddress);
bool allowExecute = false;
_loginAttempts++;
while (_loginAttempts <= AllowedRetries)
{
return;
}
if (HttpRuntime.Cache[key] == null)
{
HttpRuntime.Cache.Add(key,
true,
null,
DateTime.Now.AddSeconds(Seconds),
Cache.NoSlidingExpiration,
CacheItemPriority.Low,
null);
allowExecute = true;
}
if (!allowExecute)
{
if (String.IsNullOrEmpty(Message))
{
Message = "AllowedRetries Exceeded. You have to wait {n} seconds.";
}
filterContext.Result = new ContentResult
{
// TODO: Redirect message text to login-view
Content = Message.Replace("{n}" , Seconds.ToString())
};
filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.Conflict;
}
}
}
LoginController:
[Throttle(Name = "LoginThrottle", Seconds = 10, AllowedRetries = 3)]
[HttpPost]
public ActionResult Index(LoginViewModel model)
{
...login logic...
return View(model);
}
UPDATE
Following @lin's suggestion I got the information I wanted, but I'm not able to display it in my view. In my cshtml file I start by setting a variable before referencing it further down in my markup:
@{
var informationToUser = ViewBag.Information ?? "";
}
<div class="panel panel-primary>
...
<p>@informationToUser</p>
</div>
Still, nothing happens :( As mentioned in comments below, my url now looks like this: http://localhost:54508/?information=AllowedRetries%20Exceeded.%20You%20have%20to%20wait%2010%20seconds.