Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling enum default value as action parameter

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

like image 680
Sergio Avatar asked May 14 '26 16:05

Sergio


2 Answers

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

like image 50
Sergio Avatar answered May 17 '26 04:05

Sergio


Make the enum type nullable:

public ActionResult MyPage(MyUrls? parameter = MyUrls.Url1)
{
    if (!parameter.HasValue) {
       return HttpNotFound();
    }
    return View("MyView");
}
like image 32
ErikE Avatar answered May 17 '26 05:05

ErikE



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!