开发者

How to redirect by throwing an exceptions from an Asp.NET controller?

开发者 https://www.devze.com 2022-12-28 14:30 出处:网络
My controllers all extend a basic UserAwareController cla开发者_如何学编程ss, that exposes GetCurrentUser() method. I would like any call to this method to redirect to the login page if the user is no

My controllers all extend a basic UserAwareController cla开发者_如何学编程ss, that exposes GetCurrentUser() method. I would like any call to this method to redirect to the login page if the user is not already logged in.

Can I accomplish this by throwing some exception from this method? How can I cause a redirect to happen when this exception is thrown?


While I think that you should change approach to solution about authorization, you can stay with it and use this code:

public partial class BaseUserAwareController : Controller
{
    protected override void OnAuthorization(AuthorizationContext filterContext)
    {
        if (GetCurrentUser() == null)
        {
            filterContext.Result = new HttpUnauthorizedResult();
        }
    }
}

If your project is not too big, think about changing it to use [Authorize]. If you used it, it would be only:

[Authorize]
public partial class UserAwareController : Controller
{

}

You may think that this is not that big difference, but [Authorize] handles also some caching issues (returning cached response when you are not authorized anymore).

Install MVC 2 and create new MVC 2 web application. It contains authorization logic that you can propably use in your application.


Why not just use the Redirect or RedirectToAction methods to redirect to your login page:

public ActionResult GetCurrentUser()
{
  if (user is not logged in)
  {
      Redirect("/LoginPage");
   }
}

EDIT: Or do the check in the base controller OnActionExecuting:

public class BaseController : Controller
{
    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (GetCurrentUser() == null)
        {
            (filterContext.Controller as BaseController).Redirect("/Login");
        }

        base.OnActionExecuting(filterContext);
    }

}

http://forums.asp.net/t/1239842.aspx is also a good reference to this topic as well.


In your base controller, override OnActionExecuting. This gives you access to the ActionExecutingContext, which contains the HttpContext and thus the Response.

You can then redirect the user based on whatever logic you want like so:

<ActionContext>.HttpContext.Response.Redirect(<Your Url>)

I forget the name of the context variable offhand, but it's in the method signature.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号