3

我在引用 f# web api 库的 c# mvc 项目中收到“无法从程序集 MyApp.Api 加载类型 MyApp.Api.App”运行时错误。c# 项目 MyApp.Web 有对 F# 项目 MyApp.Api 的项目引用,并且没有编译错误。可能是什么问题?

项目 MyApp.Api 中的 App.fs

namespace MyApp.Api

open System
open System.Web
open System.Web.Mvc
open System.Web.Routing
open System.Web.Http
open System.Data.Entity
open System.Net.Http.Headers

open System.Net.Http.Headers

type Route = { controller : string; action : string; id : UrlParameter }
type ApiRoute = { id : RouteParameter }

type App() =
    inherit System.Web.HttpApplication() 

    static member RegisterGlobalFilters (filters:GlobalFilterCollection) =
        filters.Add(new HandleErrorAttribute())

    static member RegisterRoutes(routes:RouteCollection) =
        routes.IgnoreRoute( "{resource}.axd/{*pathInfo}" )
        routes.MapHttpRoute( "DefaultApi", "api/{controller}/{id}", 
            { id = RouteParameter.Optional } ) |> ignore
        routes.MapRoute("Default", "{controller}/{action}/{id}", 
            { controller = "Home"; action = "Index"; id = UrlParameter.Optional } ) |> ignore

    member this.Start() =
        AreaRegistration.RegisterAllAreas()
        App.RegisterRoutes RouteTable.Routes
        App.RegisterGlobalFilters GlobalFilters.Filters

还有我在 MyApp.Web 中的 global.asax.cs

using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using MyApp.Api;

namespace MyApp.Web
{
    public class WebApiApplication :  MyApp.Api.App// System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            base.Start();
        }

    }
}
4

1 回答 1

2

您正在错误地注册您的 api 路由。虽然 API 看起来很相似,但它们并不相似。您需要使用HttpConfiguration实例注册您的 Web API 路由:

GlobalConfiguration.Configuration.Routes.MapHttpRoute("", "", ...)

您正在尝试将 Web API 路由映射到 MVCRouteTable中。我真的很惊讶你没有收到编译错误。


因此,上述情况似乎并非如此。当我之前尝试没有引入 Dan Mohl 的项目模板时,我一定没有包含适当的命名空间。

您已将您的MyApp.Api.App类型子类化为Global.asax.cs. 丹的模板不包括这个。相反,他的模板将标记修改Global.asax如下:

<%@ Application Inherits="MyApp.Api.App" Language="C#" %>
<script Language="C#" RunAt="server">

  protected void Application_Start(Object sender, EventArgs e) {
      base.Start();
  }

</script>

这似乎工作得很好。我还有以下工作:

<%@ Application Inherits="MyApp.Web.WebApiApplication" Language="C#" %>
<!-- The following seems to be optional; just an extra, duplicate event handler.
     I was able to run the app with this script and without. -->
<script Language="C#" RunAt="server">

  protected void Application_Start(Object sender, EventArgs e) {
      base.Start();
  }

</script>

请注意,您需要完整的命名空间,而不仅仅是类型名称。如果它工作正常,那么我认为更多的代码是必要的,因为我找不到任何其他错误。

于 2013-02-20T00:31:07.563 回答