PedroSouki PedroSouki - 2 months ago 10
ASP.NET (C#) Question

How can protect the Asp.Net MVC 5 in the Edit action route from throwing unhandled exception?

I have a standard Edit action in Asp.Net MVC 5 and I want to avoid throwing the unhandled exception when a get request is made without the id like

~/food/edit
, so I did this.

public ActionResult Edit(int id = 0)
{
if (id == 0)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}

string result = _foodAppService.GetById(id);
FoodVm food = string.IsNullOrEmpty(result)
? null
: JsonConvert.DeserializeObject<FoodVm>(result);

if (food == null)
{
return RedirectToAction("Index");
}

return View(food);
}


My question is: Is it a good practice to handled it in this way or there are more suitable strategies ?

I'm new to this asking question thing, if a should I ask in another way, just let me know, thank you for your time.

Answer

In case zero could be valid its better to do

public ActionResult Edit(int? id)
{
    if (!id.HasValue)
    {
        return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
    }
}