Pergunta

I have two action methods that are called using the same action name, however, depending on the actual parameter type depends which method should be called. This causes ambiguity. I created an attribute that determines if the parameter is a Guid and is the appropriate method.

[RequiredGuidParameter(ParameterName = "title")]
[ActionName("Title")]
public ActionResult Item_ById(Guid id)
{ ... }

[ActionName("Title")]
public ActionResult Item_ByName(string id)
{ ... }

The attribute looks like this:

    public string ParameterName = string.Empty;

    public override bool IsValidForRequest(ControllerContext controllerContext, System.Reflection.MethodInfo methodInfo)
    {
        object parameter = null;
        try
        {
            parameter = controllerContext.RouteData.GetRequiredString(ParameterName) as object;
            if (parameter != null)
            {
                Guid guid;
                return Guid.TryParse((string)parameter, out guid);
            }
        }
        catch { }

        parameter = controllerContext.RequestContext.HttpContext.Request[ParameterName] as object;
        if (parameter != null)
        {
                Guid guid;
                return Guid.TryParse((string)parameter, out guid);
        }

        return false;
    }

The ultimate goal being that if the parameter is a Guid run this method, otherwise move on, in which case it finds the next one. Is there a better way that does not invlove creating an additional route? Or perhaps a better way all around?

Foi útil?

Solução

Why not something like:

public ActionResult Item_Search(string id, Guid guid)
{
    if( string.IsNullOrWhiteSpace(id) 
         SearchById();
     if( guid != new Guid() )
         SearchByGuid()
}

Non warranty'd psuedo code /\

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top