How can I avoid AmbiguousMatchException between two controller actions?

早过忘川 提交于 2019-12-18 04:39:13

问题


I have two controller actions with the same name but with different method signatures. They look like this:

    //
    // GET: /Stationery/5?asHtml=true
    [AcceptVerbs(HttpVerbs.Get)]
    public ContentResult Show(int id, bool asHtml)
    {
        if (!asHtml)
            RedirectToAction("Show", id);

        var result = Stationery.Load(id);
        return Content(result.GetHtml());
    }

    //
    // GET: /Stationery/5
    [AcceptVerbs(HttpVerbs.Get)]
    public XmlResult Show(int id)
    {
        var result = Stationery.Load(id);
        return new XmlResult(result);
    }

My unit tests have no issue with calling one or the other controller action, but my test html page throws a System.Reflection.AmbiguousMatchException.

<a href="/Stationery/1?asHtml=true">Show the stationery Html</a>
<a href="/Stationery/1">Show the stationery</a>

What needs to change to make this work?


回答1:


Just have one method like this.

[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Show(int id, bool? asHtml)
{
    var result = Stationery.Load(id);

    if (asHtml.HasValue && asHtml.Value)
        return Content(result.GetHtml());
    else
        return new XmlResult(result);
}



回答2:


Heres a link you may find userful. It talks about overloading the MVC Controllers.




回答3:


There are two ways to address this:

1> Change the method name. 2> Provide different ActionName attributes to the two methods. You can define your own attribute.




回答4:


There is the ActionName attribute. Take a look.




回答5:


To overcome this problem you can write an ActionMethodSelectorAttribute that examines the MethodInfo for each action and compares it to the posted Form values and then rejects any method for which the form values don't match (excluding the button name, of course).

Here's an example:- http://blog.abodit.com/2010/02/asp-net-mvc-ambiguous-match/

You could also make a simpler ActionMethodSelectorAttribute which looks only at the submit button name but that would tie your controller and view more closely.



来源:https://stackoverflow.com/questions/732205/how-can-i-avoid-ambiguousmatchexception-between-two-controller-actions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!