我在我的控制器和我在互聯網上找到的視圖中使用了一個助手。該助手在我的控制器「Url.SiteRoot();」中被這樣調用 如何讓我的控制器在每次調用幫助器時不拋出異常?我正在使用MVCContrib和moq進行單元測試。MVC模擬HttpContextBase在幫手中使用
我想在助手中實現某種檢查,但它感覺像MVCContrib框架或moq應該能夠處理這個,所以我不需要添加異常代碼在我的助手只是爲了能夠通過單元測試。
你可以在這裏看到助手代碼: -
namespace System.Web.Mvc {
public static class UrlHelpers {
public static string SiteRoot(HttpContextBase context) {
return SiteRoot(context, true);
}
public static string SiteRoot(HttpContextBase context, bool usePort) {
var Port = context.Request.ServerVariables["SERVER_PORT"];
if (usePort) {
if (Port == null || Port == "80" || Port == "443")
Port = "";
else
Port = ":" + Port;
}
var Protocol = context.Request.ServerVariables["SERVER_PORT_SECURE"];
if (Protocol == null || Protocol == "0")
Protocol = "http://";
else
Protocol = "https://";
var appPath = context.Request.ApplicationPath;
if (appPath == "/")
appPath = "";
var sOut = Protocol + context.Request.ServerVariables["SERVER_NAME"] + Port + appPath;
return sOut;
}
public static string SiteRoot(this UrlHelper url) {
return SiteRoot(url.RequestContext.HttpContext);
}
public static string SiteRoot(this ViewPage pg) {
return SiteRoot(pg.ViewContext.HttpContext);
}
public static string SiteRoot(this ViewUserControl pg) {
var vpage = pg.Page as ViewPage;
return SiteRoot(vpage.ViewContext.HttpContext);
}
public static string SiteRoot(this ViewMasterPage pg) {
return SiteRoot(pg.ViewContext.HttpContext);
}
public static string GetReturnUrl(HttpContextBase context) {
var returnUrl = "";
if (context.Request.QueryString["ReturnUrl"] != null) {
returnUrl = context.Request.QueryString["ReturnUrl"];
}
return returnUrl;
}
public static string GetReturnUrl(this UrlHelper helper) {
return GetReturnUrl(helper.RequestContext.HttpContext);
}
public static string GetReturnUrl(this ViewPage pg) {
return GetReturnUrl(pg.ViewContext.HttpContext);
}
public static string GetReturnUrl(this ViewMasterPage pg) {
return GetReturnUrl(pg.Page as ViewPage);
}
public static string GetReturnUrl(this ViewUserControl pg) {
return GetReturnUrl(pg.Page as ViewPage);
}
}
}