开发者

Catching and resolving AmbiguousMatchException

开发者 https://www.devze.com 2023-02-10 14:30 出处:网络
I would like to catch the AmbiguousMatchException whenever it is thrown and then write some code to resolve it. For example, I have an action ChangePassword which should be called only if the user is

I would like to catch the AmbiguousMatchException whenever it is thrown and then write some code to resolve it. For example, I have an action ChangePassword which should be called only if the user is logged in. I have another method RenewPassword which must be called if the user is not logged in. I have given the same action name to both these methods.

    [HttpPost]
    [ActionName("ChangePassword")]
    public ActionResult RenewPassword(ChangePasswordModel model)
    {
        ...
    }

    [Authorize]
    [HttpPost]
    [Action开发者_高级运维Name("ChangePassword")]
    public ActionResult ChangePassword(ChangePasswordModel model)
    {
        ...
    }

I want to use the same action name because I do not want the view to have to worry about which action to call. I know that I can write a custom FilterAttribute which will do the reverse of what AuthorizeAttribute does, apply it to the RenewPassword method, and thereby resolve the ambiguity. However, this seems like too much work for a very simple need.

Any better ideas? Is there a built in way to say that a particular action should be executed only for anonymous users and not for logged in users?


If you don't views having to worry about which action to call why not writing a reusable HTML helper:

public static class HtmlExtensions
{
    public static MvcForm BeginChangePasswordForm(this HtmlHelper htmlHelper)
    {
        if (htmlHelper.ViewContext.HttpContext.User.Identity.IsAuthenticated)
        {
            return htmlHelper.BeginForm("ChangePassword", "SomeController");
        }
        return htmlHelper.BeginForm("RenewPassword", "SomeController");
    }
}

and inside your view:

@using (Html.BeginChangePasswordForm())
{
    ...
}

and in the corresponding controller:

[HttpPost]
public ActionResult RenewPassword(ChangePasswordModel model)
{
    ...
}

[Authorize]
[HttpPost]
public ActionResult ChangePassword(ChangePasswordModel model)
{
    ...
}
0

精彩评论

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

关注公众号