在IIS中将Web API添加为子/嵌套应用程序

时间:2015-01-08 07:34:31

标签: asp.net iis asp.net-web-api asp.net-web-api2

重新创建此问题的步骤:

  1. 在IIS内部创建一个新的.net 4网站(此处称为父网站)。 将测试图像放在本网站的文件夹中,然后观察即可 在浏览器中成功申请
  2. 在指向WebAPI 2项目的父项下添加新的虚拟目录或应用程序
  3. 尝试使用www.path-to-parent-site.com/api/something/or/other
  4. 在浏览器中访问API

    我收到以下错误:

     System.Web.Routing.UrlRoutingModule does not implement IHttpHandlerFactory or IHttpHandler.
    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
    
    Exception Details: System.Configuration.ConfigurationErrorsException: System.Web.Routing.UrlRoutingModule does not implement IHttpHandlerFactory or IHttpHandler.
    
    Source Error:
    
    An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
    
    Stack Trace:
    
    
    [ConfigurationErrorsException: System.Web.Routing.UrlRoutingModule does not implement IHttpHandlerFactory or IHttpHandler.]
       System.Web.Configuration.HandlerFactoryCache.GetHandlerType(String type) +12328272
       System.Web.Configuration.HandlerFactoryCache..ctor(String type) +27
       System.Web.HttpApplication.GetFactory(String type) +94
       System.Web.MaterializeHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +375
       System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +288
    
    
    Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.34209 
    

    我能做些什么来让这个工作吗?我可以找到关于这个特定问题的非常少的相关信息,对于那些看到此错误的人来说,解决方案的解决方案更少。

    注意:如果我将WebAPI 2项目添加为IIS中的新网站,它可以很好地工作;只有在它作为子项嵌套(虚拟目录或应用程序具有相同问题)时才会发生这种情况。

    由于

2 个答案:

答案 0 :(得分:0)

WebApi不应该托管在虚拟目录上,如果你想这样做,你需要使路由模式动态化,并从虚拟目录中加载第一部分。

var virtualDirectory = request.ApplicationPath;
routes.MapHttpRoute(
    name: "API Default",
    routeTemplate: virtualDirectory + "/api/{controller}/{id}",
    defaults: new {
        id = RouteParameter.Optional
    }
);

答案 1 :(得分:0)

即使API托管在parentsite.com/childvirtualdirectory/api中,您也需要使用childvirtualdirectory

在我的场景中,我在IIS中设置了parentsite/api,然后才能访问Web API,我需要使用http://parentsite/api/api/<<controller>>