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
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
Make the enum type nullable:
public ActionResult MyPage(MyUrls? parameter = MyUrls.Url1)
{
if (!parameter.HasValue) {
return HttpNotFound();
}
return View("MyView");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With