Reputation: 113
I created a basic MVC 4 project. Added the HomeController and Home\Index.cshtml and ContactUs.cshtml. Add route in Global.asax for ContactUs.
Add a Folder Auth and add a class Auth.css in Auth folder.
using System;
using System.Web;
using System.Web.Http;
using System.Net.Http;
namespace MvcApplicationTestProject1
{
public class AuthAttribute : AuthorizeAttribute
{
//public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
//{
// HandleUnauthorizedRequest(actionContext);
//}
protected override void HandleUnauthorizedRequest(System.Web.Http.Controllers.HttpActionContext actionContext)
{
var response = actionContext.Request.CreateResponse(System.Net.HttpStatusCode.Redirect);
response.Headers.Add("Location", "http://www.google.com");
actionContext.Response = response;
}
//MVC 4 Web.Http.AuthorizeAttribute has IsAuthorized function but not AuthorizeCore
protected override bool IsAuthorized(System.Web.Http.Controllers.HttpActionContext actionContext)
{
return false;
}
}
}
In HomeController
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
return View();
}
//
// GET: /Home/
[Auth]
public ActionResult ContactUs()
{
return View();
}
}
The problem is when run the code and visit http://localhost:[port number here]/Home/ContactUs, it does not hit on the override class AuthAttribute.
Does the code have something wrong?
Upvotes: 11
Views: 14190
Reputation: 15797
Your comment says you are trying to achieve what is in this post, and yet you copied code not from that post at all, but from a previous SO post: Using custom authorization in MVC 4 that was referring to Web API. And in reading that post you see the difference is in what AuthorizeAttribute you use. You are using System.Web.Http
instead of System.Web.Mvc
.
If you used the code that you referred to in your comment, then you'd find it would work:
using System.Web;
using System.Web.Mvc;
namespace MvcApplicationTestProject1
{
public class AuthAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
return false;
}
}
}
Upvotes: 18