在ASP.NET/WCF共用元件中,發現在WCF中要透過HttpContext.Current.Server.MapPath查詢實體目錄會發生錯誤。爬文發現,當未開啟ASP.NET相容模式時(aspNetCompatibilityEnabled="true"),WCF將不支援HttpContext, HttpApplication,大部分文章都建議修改<serviceHostingEnvironment aspNetCompatibilityEnabled="true">使WCF可適用ASP.NET傳統做法。

然而,若你不想因此增加config WCF時的額外需求,可考慮改用HostingEnvironment.MapPath 方法取代Server.MapPath():

string t1 = System.Web.HttpContext.Current.Server.MapPath("~");
//以上寫法在WCF未開aspNetCompatibilityEnabled時,
//會因HttpContext.Current == null發生錯誤
        
string t2 = System.Web.Hosting.HostingEnvironment.MapPath("~");
//以上寫法,在WCF與ASP.NET都可運行無誤

Comments

Be the first to post a comment

Post a comment


86 + 8 =