gpt4 book ai didi

c# - ASP.NET MVC F# Controller 操作忽略参数

转载 作者:行者123 更新时间:2023-11-30 20:12:19 24 4
gpt4 key购买 nike

我有一个 C# ASP.NET MVC 项目,但我的 Controller 是用 F# 编写的。

由于某些原因,以下代码不能正常工作:

namespace MvcApplication8.Controllers

open System.Web.Mvc

[<HandleError>]
type ImageController() =
inherit Controller()

member x.Index (i : int) : ActionResult =
x.Response.Write i
x.View() :> ActionResult

Action 的参数貌似被忽略了...

http://localhost:56631/Image/Index/1

此错误消息的结果:

The parameters dictionary contains a null entry for parameter 'i' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Index(Int32)' in 'MvcApplication8.Controllers.ImageController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.

Parameter name: parameters

Controller 在其他方面工作正常。我知道很多人都编写过 F# MVC 代码,那么您知道我哪里出错了吗?

最佳答案

问题是 Controller 的参数名称需要与指定如何将 URL 转换为 Controller 调用的映射中指定的名称相匹配。

如果你查看 Global.asax.cs文件(您也应该能够将其转换为 F#),那么您将看到如下内容:

routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index",
id = UrlParameter.Optional } // Parameter defaults
);

名字id指定参数的预期名称,因此您需要调整 F# 代码以采用名为 id 的参数像这样:

member x.Index(id:int) =
x.ViewData.["Message"] <- sprintf "got %d" id
x.View() :> ActionResult

您可以使用 Nullable<int>如果您想让参数成为可选参数,请键入。

对于习惯了 F# 提供的静态类型安全的程序员来说,ASP.NET MVC 依赖如此多的编译时未检查的动态测试有点令人惊讶。我希望有一天,会有一些更好的 F# web 框架 :-)。

关于c# - ASP.NET MVC F# Controller 操作忽略参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2755683/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com