代码改变世界

基于Spring.NET的MVC应用程序发布时的虚拟路径错误的解决方案

2013-03-11 11:09  GPS视频平台产品经理  阅读(1257)  评论(0编辑  收藏  举报

使用spring.NET1.3以上版本时,如果web程序没有部署在根目录下,会出现虚拟路径的错误。错误如下:

虚拟路径“/saas2/currentcontext.dummy”映射到另一个应用程序,这是不允许的。

 

费力好长时间,都没有解决问题,跑到spring.NET论坛上才找到解决问题的方案,方案如下:

<spring>
    <context name="saas2" type="Spring.Context.Support.WebApplicationContext, Spring.Web">
      <resource uri="file://~/Config/controller.xml"/>
      <!--
      <resource uri="assembly://saas/saas.Config/Controller.xml"/>
      -->
      <resource uri="file://~//Dao_Saas.xml"/>
      <resource uri="assembly://saas.util/saas.Util.Config/QueryService.xml"/>
      <resource uri="assembly://saas.Service/saas.Config/Service.xml"/>
    </context>
  </spring>

  其实就是在Context的标签上写上你的虚拟路径。<context name="saas2" ></context>

 如果要自动识别,而不是发布在不同的虚拟目录下都要设置一遍,就需要自己写一个ContextHandler类了,如下所示:

using System;
using System.Xml;
using System.Web;
using System.Reflection;
using Spring.Context.Support;
using Common.Logging;

namespace Spring.Context.Support
{
    public class AutoNamedContextHandler : ContextHandler
    {
        protected ILog logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        protected override string GetContextName(object configContext, XmlElement contextElement)
        {
            string res = base.GetContextName(configContext, contextElement);
            if (string.IsNullOrEmpty(res) == false)
            {
                logger.Info("Using declared context name: " + res);
                return res;
            }

            string appPath = HttpContext.Current.Request.ApplicationPath;
            logger.Info("Using discovered context name: " + appPath);
            return appPath;
        }
    }
}

  然后将此类配置在web.config配置文件的spring节中就可以了。这样就可以自由发布了。

<?xml version="1.0"?>
<configuration>
  <configSections>
    <sectionGroup name="spring">
      <section name="context" type="Spring.Context.Support.AutoNamedContextHandler, Tools" />
    </sectionGroup>
  </configSections>
  <spring>
    <context type="Spring.Context.Support.WebApplicationContext, Spring.Web">
      <!-- ... -->
    </context>
  </spring>
</configuration>