Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC 4 - LogOff controller action giving 404 not found

I'm just wrapping up a college project, I'm not sure if I've been staring at my computer for too long and am missing something obvious, but when I try to log a user out, I'm getting a 404 not found for the URL /Account/LogOff.

I have a navbar that shows Log in/Log out depending on whether a user is, logged in, or, logged out:

<div class="nav-collapse collapse">
    <ul class="nav pull-right">
        <li class="dropdown" id="dropdown-login-div">
            @if (!Request.IsAuthenticated)
            {
                <a class="dropdown-toggle" href="#" data-toggle="dropdown">Sign In <strong class="caret"></strong></a>
            }
            else
            {
                @Html.ActionLink("Log Off", "LogOff", "Account")
            }
            <div class="dropdown-menu" id="dropdown-login">
                @Html.Partial("~/Views/Account/_LoginPartial.cshtml", new ViewDataDictionary<LetLord.Models.LoginModel>())
            </div>
        </li>
    </ul>
</div>

In my Account controller the default LogOff action that comes with the Internet template:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LogOff()
{
    WebSecurity.Logout();

    return View("Index");
}

Could someone tell me why this happening - before I throw my laptop against the wall. Cheers.

like image 355
MattSull Avatar asked Apr 15 '13 17:04

MattSull


People also ask

How to handle 404 error in c#?

Fortunately you don't need to parse the customErrors section to get name of the custom 404 page. Just throw HttpException: throw new HttpException(404, "Page you requested is not found"); ASP.NET run-time will catch the exception and will redirect to the custom 404.

How to resolve 404 error in web api?

A simple solution is to check for the HTTP status code 404 in the response. If found, you can redirect the control to a page that exists. The following code snippet illustrates how you can write the necessary code in the Configure method of the Startup class to redirect to the home page if a 404 error has occurred.


1 Answers

You use a link (<a/> tag) to log off which results in HTTP GET request when user clicks on it, but your action is constrained to serve POST request only (because it is decorated with [HttpPost] attribute).

You either need to put your link into a form and generate POST request, or remove [HttpPost] and [ValidateAntiForgeryToken] (credits to GalacticCowboy) from your action.

like image 88
THX-1138 Avatar answered Sep 20 '22 14:09

THX-1138