asp.net mvc是一个极具可扩展开发框架,在这篇文章中我将通过它的扩展实现与entlib的集成,并提供一个完整的解决异常处理解决方案。
entlib的异常处理应用块(exception handling application block)是一个不错的异常处理框架,它使我们可以采用配置的方式来定义异常处理策略。而asp.net mvc是一个极具可扩展开发框架,在这篇文章中我将通过它的扩展实现与entlib的集成,并提供一个完整的解决异常处理解决方案。
一、基本异常处理策略
我们首先来讨论我们的解决方案具体采用的异常处理策略:
对于执行controller的某个action方法抛出的异常,我们会按照指定配置策略进行处理。我们可以采取日志记录、异常替换和封装这些常用的异常处理方式;
对于处理后的异常,如果异常处理策略规定需要将其抛出,则会自动重定向到与异常类型匹配的出错页面。我们会维护一个异常类型和error view的匹配关系;
对于处理后的异常,如果异常处理策略规定不需要将其抛出,则会执行与当前action操作相匹配的错误处理action进行处理。异常处理action方法默认采用“on{action}error”这样的命名规则,而当前上下文会与异常处理操作方法的参数进行绑定。除次之外,我们会设置当前modelstate的错误信息;
如果用户不曾定义相应的异常处理action,依然采用“错误页面重定向”方式进行异常处理。
二、通过自定义action处理异常
为了让读者对上面介绍的异常处理页面有一个深刻的理解,我们来进行一个实例演示。该实例用于模拟用户登录,我们定义了如下一个只包含用户名和密码两个属性的model:logininfomodel。
namespace artech.mvc.exceptionhandling.models
{
public class logininfo
{
[display(name ="user name")]
[required(errormessage = "user name is manadatory!")]
public string username { get; set; }
[display(name = "password")]
[datatype(datatype.password)]
[required(errormessage = "password is manadatory!")]
public string password { get; set; }
}
}
我们定义了如下一个accountcontroller,它是我们自定义的basecontroller的子类。accountcontroller在构造的时候调用基类构造函数指定的参数代表异常处理策略的配置名称。signin方法代表用于进行“登录”的操作,而onsigninerror就表示该操作对应的异常处理操作。如果在signin操作中抛出的异常经过处理后无需再抛出,则会通过调用onsigninerror,而此时modelstate已经被设置了相应的错误消息。
public class accountcontroller basecontroller
{
public accountcontroller()
base("mypolicy")
{ }
public actionresult signin()
{
return view(new logininfo());
}
[httppost]
public actionresult signin(logininfo logininfo)
{
if (!modelstate.isvalid)
{
return this.view(new logininfo { username = logininfo.username });
}
if (logininfo.username != "foo")
{
throw new invalidusernameexception();
}
if (logininfo.password != "password")
{
throw new usernamepasswordnotmatchexception();
}
viewbag.message = "authentication succeeds!";
return this.view(new logininfo { username = logininfo.username });
}
public actionresult onsigninerror(string username)
{
return this.view(new logininfo { username = username });
}
}
具体定义在signin操作方法中的认证逻辑是这样的:如果用户名不是“foo”则抛出invalidusernameexception异常;如果密码不是“password”则抛出usernamepasswordnotmatchexception异常。下面是signin操作对应的view的定义:
@model artech.mvc.exceptionhandling.models.logininfo
@{
viewbag.title = "signin";
}
@html.validationsummary()
@if (viewbag.messages != null)
{
@viewbag.messages
}
@using (html.beginform())
{
@html.editorformodel()
<input type="submit" value="signin" />
}
在accountcontroller初始化时指定的异常处理策略“mypolicy”定义在如下的配置中。我们专门针对signin操作方法抛出的invalidusernameexception和usernamepasswordnotmatchexception进行了处理,而errormessagesettinghandler是我们自定义的异常处理器,它仅仅用于设置错误消息。如下面的代码片断所示,如果上述的这两种类型的异常被抛出,最终的错误消息会被指定为“user name does not exist!”和“user name does not match password!”。
<exceptionhandling>
<exceptionpolicies>
<add name="mypolicy">
<exceptiontypes>
<add name="invalidusernameexception"
type="artech.mvc.exceptionhandling.models.invalidusernameexception, artech.mvc.exceptionhandling"
posthandlingaction="none">
<exceptionhandlers>
<add name="errormessagesettinghandler"
type="artech.mvc.exceptionhandling.errormessagesettinghandler, artech.mvc.exceptionhandling"
errormessage="user name does not exist!"/>
</exceptionhandlers>
</add>
<add name="usernamepasswordnotmatchexception"
type="artech.mvc.exceptionhandling.models.usernamepasswordnotmatchexception, artech.mvc.exceptionhandling"
posthandlingaction="none">
<exceptionhandlers>
<add name="errormessagesettinghandler"
type="artech.mvc.exceptionhandling.errormessagesettinghandler, artech.mvc.exceptionhandling"
errormessage="user name does not match password!"/>
</exceptionhandlers>
</add>
</exceptiontypes>
</add>
</exceptionpolicies>
</exceptionhandling>
现在我们通过路由映射将accountcontroller和sign设置为默认controller和action后,开启我们的应用程序。在输入错误的用户名和错误明码的情况下在validationsummary中将自动得到相应的错误消息。
三、通过配置的error view处理异常
在上面的配置中,针对invalidusernameexception和usernamepasswordnotmatchexception这两种异常类型的配置策略都将posthandlingaction属性设置为“none”,意味着不会将原来的异常和处理后的异常进行重新抛出。现在我们将该属性设置为“thrownewexception”,意味着我们会将处理后的异常重新抛出来。
<exceptionhandling>
<exceptionpolicies>
<add name="mypolicy">
<exceptiontypes>
<add name="invalidusernameexception" type="artech.mvc.exceptionhandling.models.invalidusernameexception, artech.mvc.exceptionhandling"
posthandlingaction="thrownewexception">
...
<add name="usernamepasswordnotmatchexception" type="artech.mvc.exceptionhandling.models.usernamepasswordnotmatchexception, artech.mvc.exceptionhandling"
posthandlingaction="thrownewexception">
...
</add>
</exceptiontypes>
</add>
</exceptionpolicies>
</exceptionhandling>
按照我们上面的异常处理策略,在这种情况下我们将采用“错误页面”的方式来进行异常处理。也handleerrorattribute的处理方式类似,我们支持异常类型和error view之间的匹配关系,而这是通过类似于如下的配置来定义的。值得一提的是,这里的异常类型是经过处理后重新抛出的异常。
<artech.exceptionhandling>
<add exceptiontype="artech.mvc.exceptionhandling.models.invalidusernameexception, artech.mvc.exceptionhandling"
errorview="invalideusernameerror"/>
<add exceptiontype="artech.mvc.exceptionhandling.models.usernamepasswordnotmatchexception, artech.mvc.exceptionhandling"
errorview="usernamepasswordnotmatcherror"/>
</artech.exceptionhandling>
如上面的配置所示,我们为invalidusernameexception和usernamepasswordnotmatchexception这两种异常类型定义了不同的error view,分别是“invalideusernameerror”和“usernamepasswordnotmatcherror”,详细定义如下所示:
@{
layout = null;
}
<!doctype html>
<html>
<head>
<title>error</title>
</head>
<body>
<p style="colorred; font-weightbold">sorry,the user name you specify does not exist!</p>
</body>
</html>
@{
layout = null;
}
<!doctype html>
<html>
<head>
<title>error</title>
</head>
<body>
<p style="colorred; font-weightbold">sorry, the password does not match the given user name!</p>
</body>
</html>
现在我们按照上面的方式运行我们的程序,在分别输入错误的用户名和密码的情况下会自动显现相应的错误页面。
四、自定义actioninvoker:exceptionactioninvoker
对于上述的两种不同的异常处理方式最终是通过自定义的actioninvoker来实现的,我们将其命名为exceptionactioninvoker。如下面的代码片断所式,exceptionactioninvoker直接继承自controlleractioninvoker。属性exceptionpolicy是一个基于指定的异常策略名称创建的exceptionpolicyimpl 对象,用于针对entlib进行的异常处理。而属性geterrorview是一个用于获得作为错误页面的viewresult对象的委托。整个异常处理的核心定义在invokeaction方法中,该方法中指定的handleerroractionname参数代表的是“异常处理操作名称”,整个方法就是按照上述的异常处理策略实现的。
using system;
using system.collections.generic;
using system.linq;
using system.web;
using system.web.mvc;
using artech.mvc.exceptionhandling.configuration;
using microsoft.practices.enterpriselibrary.common.configuration;
using microsoft.practices.enterpriselibrary.exceptionhandling;
namespace artech.mvc.exceptionhandling
{
public class exceptionactioninvoker controlleractioninvoker
{
protected exceptionhandlingsettings exceptionhandlingsettings{get; private set;}
protected virtual func<string, handleerrorinfo, viewresult> geterrorview { get; private set; }
public exceptionpolicyimpl exceptionpolicy { get; private set; }
public exceptionactioninvoker(string exceptionpolicy,func<string, handleerrorinfo, viewresult> geterrorview)
{
this.exceptionpolicy = enterpriselibrarycontainer.current.getinstance<exceptionpolicyimpl>(exceptionpolicy);
this.geterrorview = geterrorview;
this.exceptionhandlingsettings = exceptionhandlingsettings.getsection();
}
public override bool invokeaction(controllercontext controllercontext, string handleerroractionname)
{
exceptioncontext exceptioncontext = controllercontext as exceptioncontext;
if (null == exceptioncontext)
{
throw new argumentexception("the controllercontext must be exceptioncontext!", "controllercontext");
}
try
{
exceptioncontext.exceptionhandled = true;
if (this.exceptionpolicy.handleexception(exceptioncontext.exception))
{
handlerethrownexception(exceptioncontext);
}
else
{
if (exceptionhandlingcontext.current.errors.count == 0)
{
exceptionhandlingcontext.current.errors.add(exceptioncontext.exception.message);
}
controllerdescriptor controllerdescriptor = this.getcontrollerdescriptor(exceptioncontext);
actiondescriptor handleerroraction = findaction(exceptioncontext, controllerdescriptor, handleerroractionname);
if (null != handleerroraction)
{
idictionary<string, object> parameters = getparametervalues(controllercontext, handleerroraction);
exceptioncontext.result = this.invokeactionmethod(exceptioncontext, handleerroraction, parameters);
}
else
{
handlerethrownexception(exceptioncontext);
}
}
return true;
}
catch (exception ex)
{
exceptioncontext.exception = ex;
handlerethrownexception(exceptioncontext);
return true;
}
}
protected virtual void handlerethrownexception(exceptioncontext exceptioncontext)
{
string errorviewname = this.geterrorviewname(exceptioncontext.exception.gettype());
string controllername = (string)exceptioncontext.routedata.getrequiredstring("controller");
string action = (string)exceptioncontext.routedata.getrequiredstring("action");
handleerrorinfo handleerrorinfo = new handleerrorinfo(exceptioncontext.exception, controllername, action);
exceptioncontext.result = this.geterrorview(errorviewname, handleerrorinfo);
}
protected string geterrorviewname(type exceptiontype)
{
exceptionerrorviewelement element = exceptionhandlingsettings.exceptionerrorviews
.cast<exceptionerrorviewelement>().firstordefault(el=>el.exceptiontype == exceptiontype);
if(null != element)
{
return element.errorview;
}
if(null== element && null != exceptiontype.basetype!= null)
{
return geterrorviewname(exceptiontype.basetype);
}
else
{
return "error";
}
}
}
}
五、自定义controller:basecontroller
exceptionactioninvoker最终在我们自定义的controller基类basecontroller中被调用的。exceptionactioninvoker对象在构造函数中被初始化,并在重写的onexception方法中被调用。
using system;
using system.web.mvc;
namespace artech.mvc.exceptionhandling
{
public abstract class basecontroller controller
{
public basecontroller(string exceptionpolicy)
{
func<string, handleerrorinfo, viewresult> geterrorview = (viewname, handleerrorinfo) => this.view(viewname, handleerrorinfo);
this.exceptionactioninvoker = new exceptionactioninvoker(exceptionpolicy,geterrorview);
}
public basecontroller(exceptionactioninvoker actioninvoker)
{
this.exceptionactioninvoker = actioninvoker;
}
public virtual exceptionactioninvoker exceptionactioninvoker { get; private set; }
protected virtual string gethandleerroractionname(string actionname)
{
return string.format("on{0}error", actionname);
}
protected override void onexception(exceptioncontext filtercontext)
{
using (exceptionhandlingcontextscope contextscope = new exceptionhandlingcontextscope(filtercontext))
{
string actionname = routedata.getrequiredstring("action");
string handleerroractionname = this.gethandleerroractionname(actionname);
this.exceptionactioninvoker.invokeaction(filtercontext, handleerroractionname);
foreach (var error in exceptionhandlingcontext.current.errors)
{
modelstate.addmodelerror(guid.newguid().tostring() ,error.errormessage);
}
}
}
}
}
值得一提的是:整个onexception方法中的操作都在一个exceptionhandlingcontextscope中进行的。顾名思义, 我们通过exceptionhandlingcontextscope为exceptionhandlingcontext创建了一个范围。exceptionhandlingcontext定义如下,我们可以通过它获得当前的exceptioncontext和modelerrorcollection,而静态属性current返回当前的exceptionhandlingcontext对象。
public class exceptionhandlingcontext
{
[threadstatic]
private static exceptionhandlingcontext current;
public exceptioncontext exceptioncontext { get; private set; }
public modelerrorcollection errors { get; private set; }
public exceptionhandlingcontext(exceptioncontext exceptioncontext)
{
this.exceptioncontext = exceptioncontext;
this.errors = new modelerrorcollection();
}
public static exceptionhandlingcontext current
{
get { return current; }
set { current = value; }
}
}
在basecontroller的onexception方法中,当执行了exceptionactioninvoker的invokeaction之后,我们会将当前exceptionhandlingcontext的modelerror转移到当前的modelstate中。这就是为什么我们会通过validationsummary显示错误信息的原因。对于我们的例子来说,错误消息的指定是通过如下所示的errormessagesettinghandler 实现的,而它仅仅将指定的错误消息添加到当前exceptionhandlingcontext的errors属性集合中而已。
[configurationelementtype(typeof(errormessagesettinghandlerdata))]
public class errormessagesettinghandler iexceptionhandler
{
public string errormessage { get; private set; }
public errormessagesettinghandler(string errormessage)
{
thiserrormessage = errormessage;
}
public exception handleexception(exception exception, guid handlinginstanceid)
{
if (null == exceptionhandlingcontextcurrent)
{
throw new invalidoperationexception("");
}
if (stringisnullorempty(thiserrormessage))
{
exceptionhandlingcontextcurrenterrorsadd(exceptionmessage);
}
else
{
exceptionhandlingcontextcurrenterrorsadd(thiserrormessage);
}
return exception;
}
}
以上就是asp.net mvc对异常处理的解决方法汇总的详细内容。