Question

I have enum that looks like:

public enum MyUrls
{
    Url1 = 0,       
    Url2 = 1,       
    Url3 = 2
}

I'm using it to generate urls for some pages on my website. Base url looks like www.mysite.com/part/, also i got 3 routes:

www.mysite.com/part/Url1
www.mysite.com/part/Url2
www.mysite.com/part/Url3

The last parameter of query string is generated using UrlHelper.

Controller action looks like:

public ActionResult MyPage(MyUrls parameter = MyUrls.Url1)
{       
    return View("MyView");
}

input parameter of action has default value to make url www.mysite.com/part work. All other routes work well as expected.

The question is: How can i handle urls like www.mysite.com/part/not_existent_enum_value - it should return HttpNotFound result, and still keep page www.mysite.com/part/ as a default one

Was it helpful?

Solution

Thanks for attention, got my own answer:

public ActionResult MyPage(string parameter)
{
    var parameterValue = MyUrls.Url1;
    if (!string.IsNullOrEmpty(parameter) && !Enum.TryParse(parameter, out parameterValue))
        return HttpNotFound();
    return View("MyView");
}

parameterValue will contain default value for routing. If parameter passed to action is invalid enum value we throw error 404

OTHER TIPS

Make the enum type nullable:

public ActionResult MyPage(MyUrls? parameter = MyUrls.Url1)
{
    if (!parameter.HasValue) {
       return HttpNotFound();
    }
    return View("MyView");
}

You could try to use a IModelBinder

public class MyUrlsEnumModelBinder : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

        MyUrls temp;

        if (!Enum.TryParse(valueResult.AttemptedValue, out temp))
            return MyUrls.Url1;
        return temp;
    }
}

And within your Global.asax.cs:

    protected void Application_Start()
    {
        /*  */
        ModelBinders.Binders.Add(typeof(MyUrls), new MyUrlsEnumModelBinder());
    }

This will always set the value to MyUrls.Url1 if it is a invalid value. You controlleraction can be as followed:

  public ActionResult MyPage(MyUrls url)

In your action:

public ActionResult MyPage(MyUrls parameter = MyUrls.Url1)
{       

   if( Enum.IsDefined(typeof(MyUrls), parameter ) )
   {
      //redirect your not found url
   }

    return View("MyView");
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top