熟悉 Castle Monorail 的朋友应该对以下这段代码再熟悉不过了:
public
class
HomeController : SmartDispatcherController
{
public void Main()
{
PropertyBag[ " name " ] = " Jacky Chung " ;
if ( this .IsGet)
{
// Do something
//
}
else if ( this .IsPost)
{
// Do something
//
}
else
{
// Do something
//
}
}
}
{
public void Main()
{
PropertyBag[ " name " ] = " Jacky Chung " ;
if ( this .IsGet)
{
// Do something
//
}
else if ( this .IsPost)
{
// Do something
//
}
else
{
// Do something
//
}
}
}
其中,IsGet, IsPost属性用于判断当前HTTP的请求模式(GET或POST),它们都是继承自Controller基类的属性。
但在 ASP.NET MVC 的Controller类上并没有提供这两个属性的实现。我们只能使用以下代码来判断HTTP的请求模式:
if
(
this
.Request.HttpMethod
==
"
GET
"
)
{
// Do Something
//
}
else if ( this .Request.HttpMethod == " POST " )
{
// Do Something
//
}
else
{
// Do Something
//
}
{
// Do Something
//
}
else if ( this .Request.HttpMethod == " POST " )
{
// Do Something
//
}
else
{
// Do Something
//
}
这样的编码方式往往不是我们需要的。幸好,C#3.0 添加了Extension Method这个特性,我们可以利用该特性向
ASP.NET MVC 的 Controller类加入IsPost & IsGet 方法,以模仿Monorail的IsGet & IsPost属性。
Extension Method 的代码如下:
public
static
class
MvcUtils
{
public static bool IsPost( this Controller controller)
{
if (controller.Request.HttpMethod == " POST " )
return true ;
return false ;
}
public static bool IsGet( this Controller controller)
{
if (controller.Request.HttpMethod == " GET " )
return true ;
return false ;
}
}
{
public static bool IsPost( this Controller controller)
{
if (controller.Request.HttpMethod == " POST " )
return true ;
return false ;
}
public static bool IsGet( this Controller controller)
{
if (controller.Request.HttpMethod == " GET " )
return true ;
return false ;
}
}
Now,如果我们要使用该Extension Method, 只需要using该Method的命名空间即可,如:
using
extension
-
method
-
namespace
;
[HandleError]
public class HomeController : Controller
{
public ActionResult Index()
{
if ( this .IsGet())
{
ViewData[ " Message " ] = " Method: GET " ;
}
else if ( this .IsPost())
{
ViewData[ " Message " ] = " Method: POST " ;
}
else
{
// Do Something
//
}
return View();
}
}
[HandleError]
public class HomeController : Controller
{
public ActionResult Index()
{
if ( this .IsGet())
{
ViewData[ " Message " ] = " Method: GET " ;
}
else if ( this .IsPost())
{
ViewData[ " Message " ] = " Method: POST " ;
}
else
{
// Do Something
//
}
return View();
}
}
注意:上述代码中的this.IsGet() 方法,它并不是HomeControl类的成员方法,也不是继承于其基类的方法,而是
MvcUtils静态类的IsGet()方法。关于更多Extension Method的知识,可浏览MSDN获取。