编写HttpResponse和HttpResponseBase的扩展

Gol*_*hop 1 asp.net-mvc

我有一种情况,我想写一个可以在HttpResponse和HttpResponseBase上使用的扩展.

经过一番研究,发现两者都是兄弟姐妹,但只能通过Object类的简单扩展.

由于您只能使用一个特定的类定义Generic,因此我遇到了必须编写两次相同方法来处理两个不同对象模型的问题:Web应用程序重定向和MVC重定向.

目前的实施,虽然我不喜欢它:

public static void RedirectTo404(this HttpResponseBase response)
{
    response.Redirect("~/404.aspx");
}
public static void RedirectTo404(this HttpResponse response)
{
    response.Redirect("~/404.aspx");
}
Run Code Online (Sandbox Code Playgroud)

我想有这样的东西(我知道它在语法上不可能,但是要提出一个想法)

public static void RedirectTo404<T>(this T response) where T : HttpResponseBase , HttpResponse
{
    response.Redirect("~/404.aspx");
}
Run Code Online (Sandbox Code Playgroud)

usr*_*usr 5

通过调用版本将HttpResponse版本委托给HttpResponseBase版本new HttpResponseWrapper(response).这样可以节省您复制代码体的麻烦.

或者有一个采用动态类型参数的通用方法.我不会选择这种方法,因为它是动态输入的,没有充分的理由.

public static void RedirectTo404(this HttpResponseBase response)
{
    response.Redirect("~/404.aspx");
}
public static void RedirectTo404(this HttpResponse response)
{
    RedirectTo404(new HttpResponseWrapper(response)); //delegate to implementation
}
Run Code Online (Sandbox Code Playgroud)