【问题标题】:Ambiguous action methods in MVC 2MVC 2 中的模棱两可的动作方法
【发布时间】:2011-08-09 16:55:09
【问题描述】:

我在 MVC 2 中遇到了一些模棱两可的操作方法的问题。我已经尝试实施此处找到的解决方案:ASP.NET MVC ambiguous action methods,但这只是给我一个“找不到资源”错误,因为它认为我'我试图调用我不想想要调用的操作方法。我使用的RequiredRequestValueAttribute 类与另一个问题的解决方案中的类完全相同:

public class RequireRequestValueAttribute : ActionMethodSelectorAttribute
{
    public RequireRequestValueAttribute(string valueName)
    {
        ValueName = valueName;
    }
    public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo)
    {
        return (controllerContext.HttpContext.Request[ValueName] != null);
    }
    public string ValueName { get; private set; }
}

我的操作方法是:

    //
    // GET: /Reviews/ShowReview/ID

    [RequireRequestValue("id")]
    public ActionResult ShowReview(int id)
    {
        var game = _gameRepository.GetGame(id);

        return View(game);
    }

    //
    // GET: /Reviews/ShowReview/Title

    [RequireRequestValue("title")]
    public ActionResult ShowReview(string title)
    {
        var game = _gameRepository.GetGame(title);

        return View(game);
    }

现在,我正在尝试使用 int id 版本,而不是调用 string title 版本。

【问题讨论】:

    标签: asp.net-mvc-2 ambiguous actionmethod


    【解决方案1】:

    此解决方案假定无论您是按 ID 还是名称选择,您都必须绝对使用相同的 URL,并且您的路由设置为从 URL 向此方法传递一个值。

    [RequireRequestValue("gameIdentifier")]
    public ActionResult ShowReview(string gameIdentifier)
    {
        int gameId;
        Game game = null;
        var isInteger = Int32.TryParse(gameIdentifier, out gameId);
    
        if(isInteger)
        {
          game = _gameRepository.GetGame(gameId);
        }
        else
        {
          game = _gameRepository.GetGame(gameIdentifier);
        }
    
        return View(game);
    }
    

    更新:根据Microsoft:“Action 方法不能基于参数进行重载。Action 方法可以在使用 NonActionAttribute 或 AcceptVerbsAttribute 等属性消除歧义时进行重载。”

    【讨论】:

    • 嗯...有趣的选择。如果我找不到更干净的东西,我可能会求助于它。
    • 我不知道路由引擎根据可转换为特定类型的参数选择两种操作方法之一的干净方法。也许有人会证明我错了。
    • 是的,进一步的研究表明你是对的。感谢您的帮助!
    猜你喜欢
    • 2010-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多