hardywang
hardywang

Reputation: 5162

401 code not handled in mvc project properly

I have ASP.NET MVC4 project with custom AuthorizeAttribute to control the authorization. In order to explain my situation easier I created a dummy project to illustrate the issue.

I have one single controller

using System.Web.Mvc;
using MvcApplication2.Helper;
using MvcApplication2.Models;

namespace MvcApplication2.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            var model = new ViewModel();

            return View(model);
        }

        [HttpPost]
        public ActionResult Index(ViewModel model)
        {
            Session["ModelValue"] = model.InputValue;

            return RedirectToAction("Step2");
        }

        [MyAuthorize]
        public ActionResult Step2()
        {
            return View();
        }
    }
}

The purpose is very simple, From Index I accept some input, store the value in a session and redirect to Step2. I have my authorize attribute on step 2. The code for my attribute is

using System;
using System.Web;
using System.Web.Mvc;

namespace MvcApplication2.Helper
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
    public class MyAuthorizeAttribute : AuthorizeAttribute
    {
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (httpContext.Session["ModelValue"] == null)
            {
                return false;
            }
            else
            {
                string inputValue = httpContext.Session["ModelValue"] as string;

                if (inputValue != "1")
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
        }
    }
}

The purpose is very simple, check if the session value is 1 or not.

Run the application, you input 1 in textbox and you see step2 view, if you input anything else you get the default 401.0 page.

Now I opened the web.config file to include

  <system.web>
    <customErrors mode="On" defaultRedirect="~/Error">
      <error statusCode="401" redirect="~/401.htm" />
    </customErrors>

    <compilation debug="true" targetFramework="4.0" />

  </system.web>

I hope when the application captures 401 code, I should see the content of 401.htm. But the reality is that I still get the default 401 error display from server.

Any idea why?

Upvotes: 0

Views: 142

Answers (1)

Nemmy
Nemmy

Reputation: 121

In addition use this:

      <system.webServer>
        <httpErrors>
          <error statusCode="401" path="~/Home/Login"/>
          <error statusCode="404" path="~/Error/NotFound"/>
        </httpErrors>
</system.webServer>

Upvotes: 1

Related Questions