问题
I have the following controller auto-generated by asp.net
//
// POST: /Account/LogOff
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LogOff()
{
AuthenticationManager.SignOut();
return RedirectToAction("Index", "Home");
}
Now I have a log off button. Currently it looks like this:
<div class="userdrop">
<ul>
<li><a href="@Url.Action("Manage", "Account")">Profile</a></li>
<li><a href="@Url.Action("LogOff", "Account")">Logout</a></li>
</ul>
</div><!--userdrop-->
But it does not work and I am guessing it is cause it is a Post action method.
How would I go about "logging off" ?
[EDIT]
Why is it auto-generated as an Http Post? Is it more secure that way? Does it not send the cookie with it when it logs out?
回答1:
How would I go about "logging off" ?
By using a form instead of an anchor:
<li>
@using (Html.BeginForm("LogOff", "Account"))
{
@Html.AntiForgeryToken()
<button type="submit">Logout</button>
}
</li>
You could call the CSS wizards to style this button look like an anchor if you want. But the semantically correct element in this case is an html form which allows you to send a POST verb.
回答2:
There is no compelling reason for this to be an HttpPost
. I know it's generated that way, but you're not actually POST
ing any data. Just remove the attribute and it will work as is.
Now, if you want it to work with the HttpPost
then you'll need to wrap this in a Form
and make it a submit
button or submit
the form onclick
.
<li>
@using (Html.BeginForm("LogOff", "Account",
FormMethod.Post, new { id = "LogOffForm" }))
{
@Html.AntiForgeryToken()
<a href="@Url.Action("LogOff", "Account")"
onclick="$('#LogOffForm').submit();">Logout</a>
}
</li>
回答3:
You are right that it has to do with [HttpPost]
attribute, which only allow for HTTP POST requests to be made. Regular HTML anchors trigger HTTP GET requests, therefor your example does not work.
One solution would be something like this:
@using (Html.BeginForm("LogOff", "Account", FormMethod.Post,
new { id = "logoutForm" })) {
@Html.AntiForgeryToken()
<button type="submit">Log off</button>
}
I believe this is close to what the default template does in MVC4.
Notice how we also pass along the anti forgery token, required by the [ValidateAntiForgeryToken]
attribute.
来源:https://stackoverflow.com/questions/21406497/asp-net-mvc-post-for-url-action