【问题标题】:MVC Controller with optional parameter in F#F# 中带有可选参数的 MVC 控制器
【发布时间】:2014-09-16 17:14:18
【问题描述】:

我相应地创建带有可选参数的控制器:

type ProductController(repository : IProductRepository) =
inherit Controller()
member this.List (?page1 : int) = 
    let page = defaultArg page1 1

当我启动应用程序时,它给了我错误: "System.MissingMethodException: 没有为此对象定义无参数构造函数。"

我从依赖注入中知道这个错误,这是我的 Ninject 设置:

static let RegisterServices(kernel: IKernel) =
    System.Web.Http.GlobalConfiguration.Configuration.DependencyResolver <- new NinjectResolver(kernel)

    let instance = Mock<IProductRepository>()
                    .Setup(fun m -> <@ m.Products @>)
                    .Returns([
                                new Product(1, "Football", "", 25M, "");
                                new Product(2, "Surf board", "", 179M, "");
                                new Product(3, "Running shoes", "", 95M, "")
                    ]).Create()

    kernel.Bind<IProductRepository>().ToConstant(instance) |> ignore

    do()

问题是当我从控制器中删除我的可选参数时一切正常。当更改常规参数时,它会给我以下错误: 参数字典包含“FSharpStore.WebUI.ProductController”中方法“System.Web.Mvc.ViewResult List(Int32)”的不可为空类型“System.Int32”的参数“页面”的空条目。可选参数必须是引用类型、可空类型或声明为可选参数。 参数名称:参数

这是我的路线设置:

static member RegisterRoutes(routes:RouteCollection) =
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}")


    routes.MapRoute(
        "Default", // Route name
        "{controller}/{action}/{id}", // URL with parameters
        { controller = "Product"; action = "List"; id = UrlParameter.Optional } // Parameter defaults
    ) |> ignore

有人做过控制器的可选参数吗?我正在为我的同事开展试点项目,以将 F# 推广到我们的堆栈中。谢谢

【问题讨论】:

  • 如果您将page1 参数转换为常规int,而不是选项,您是否也会收到错误消息?
  • 你的路由配置是什么样的?你怎么称呼你的控制器?

标签: asp.net-mvc f# ninject


【解决方案1】:

另一个 F# - C# 互操作痛苦:P

F# 可选参数对于 F# 调用者来说是一个有效的可选参数,但是在 C# 中这个参数将是 FsharpOption&lt;T&gt; 对象。

在您的情况下,您必须使用Nullable&lt;T&gt;。因此,代码如下所示:

open System.Web.Mvc
open System
[<HandleError>]
type HomeController() =
    inherit Controller()    
    member this.Hello(code:Nullable<int>) =        
        this.View() :> ActionResult

【讨论】:

  • 当将此参数指定为 Nullable 时,我必须在调用中将参数显式指定为“null”,否则会收到错误“在控制器上未找到任何操作' ' 与请求相匹配。”为了能够不使用它,我必须在 F# 中显式指定一个没有参数的方法。
猜你喜欢
  • 1970-01-01
  • 2011-02-14
  • 1970-01-01
  • 1970-01-01
  • 2013-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-06
相关资源
最近更新 更多