![](/img/trans.png)
[英]Dynamic typecasting in asp.net mvc Edit action: how can I handle multiple datatypes without throwing an exception?
[英]How can protect the Asp.Net MVC 5 in the Edit action route from throwing unhandled exception?
我在Asp.Net MVC 5中有一個標准的Edit操作,並且我想避免在沒有諸如~/food/edit
類的id的情況下發出get請求時拋出未處理的異常,所以我這樣做了。
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);
}
我的問題是:以這種方式處理它是一種好的做法,還是有更合適的策略?
我是這個問題的新手,如果我應該以其他方式詢問,請告訴我,謝謝您的時間。
如果零可能是有效的,那最好做
public ActionResult Edit(int? id)
{
if (!id.HasValue)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
}
或者,可以有更多整體方法來處理MVC中的異常。 您可以使用方法OnException
覆蓋,這使您能夠在一個方法中調試控制器中的所有異常並進行處理。 只需將基類添加到所有控制器中,如下所示:
public class BaseController : Controller
{
protected override void OnException(ExceptionContext filterContext)
{
string redirectUrl;
var exception = filterContext.Exception;
if (exception is EntityException)
{
redirectUrl = "/Content/error.html";
}
else
{
redirectUrl = "/Info/Index";
}
//do whatever you wont
Response.Redirect(redirectUrl);
}
還要像Paul Swetz所說的那樣使用輸入參數驗證。 這種方法比較通用,可以攔截所有異常,並且不會向用戶顯示錯誤。
遵循@Fran的建議。 我建立了一個名為MissingParam
的動作過濾器屬性
public class MissingParamAttribute : ActionFilterAttribute
{
public string ParamName { get; set; }
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.ActionParameters.ContainsKey(ParamName))
{
if (filterContext.ActionParameters[ParamName] == null)
{
filterContext.ActionParameters[ParamName] = 0;
}
}
base.OnActionExecuting(filterContext);
}
}
在動作中,我這樣做:
[MissingParam(ParamName="id")]
public ActionResult Edit(int id)
這樣,我就無需弄亂方法參數,之前可以進行任何驗證。 此實現遵循打開/關閉原則。 我擴展了它的功能,但是並沒有像問題中的代碼那樣進行更改。
首先,最重要的是使用Try-Catch。
public ActionResult Edit(int id)
{
try
{
if (id != 0 || id!=null)
{
string result = _foodAppService.GetById(id);
FoodVm food = string.IsNullOrEmpty(result) ? null:JsonConvert.DeserializeObject<FoodVm>(result);
if (food == null)
{
return RedirectToAction("Index");
}
else
{
return View(food);
}
}
else
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
}
catch (exception ex)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.