2012-05-15 48 views
2

超载我有2种方法,下面方法控制器

public string Download(string a,string b) 
public string Download(string a) 

给出不过MVC3在IIS 5.1给出运行时错误,这2个mehods是ambiguious。

我该如何解决这个问题?

+0

你真的*需要*两种方法吗?请给更多的上下文。 –

回答

3

由于字符串可以为空,因此从MVC的角度来看,这些重载确实是模棱两可的。只需检查b是否为空(如果您想要默认值,可以将其设为可选参数)。

另一方面,您可以尝试自定义ActionMethodSelectorAttribute实现。这里有一个例子:

public class ParametersRequiredAttribute : ActionMethodSelectorAttribute 
    { 
     #region Overrides of ActionMethodSelectorAttribute 

     /// <summary> 
     /// Determines whether the action method selection is valid for the specified controller context. 
     /// </summary> 
     /// <returns> 
     /// true if the action method selection is valid for the specified controller context; otherwise, false. 
     /// </returns> 
     /// <param name="controllerContext">The controller context.</param><param name="methodInfo">Information about the action method.</param> 
     public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo) 
     { 
      var parameters = methodInfo.GetParameters(); 

      foreach (var parameter in parameters) 
      { 
       var value = controllerContext.Controller.ValueProvider.GetValue(parameter.Name); 

       if (value == null || string.IsNullOrEmpty(value.AttemptedValue)) return false; 
      } 

      return true; 
     } 

     #endregion 
    } 

用法:

[ParametersRequired] 
public string Download(string a,string b) 


// if a & b are missing or don't have values, this overload will be invoked. 
public string Download(string a)