【问题标题】:the request is invalid?请求无效?
【发布时间】:2014-03-01 07:14:42
【问题描述】:

有点 asp.net mvc noob ,我正在尝试传入一个字符串作为我的 Web API 控制器的参数:

public class ValuesController : ApiController
{
    // GET api/values
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }

    // GET api/values/5
    public string Get(int id)
    {
        return "value";
    }

    public string Get(string arg)
    {
        return "othervalue";
    }

}

我尝试添加另一条路线:

routes.MapRoute(
    name: "Default2",
    url: "{controller}/{action}/{arg}",
    defaults: new { controller = "Home", action = "Index", arg = UrlParameter.Optional }
);

所以我想保留两个 Get 方法并使用带 arg 参数的 Get,这样我就可以传入一个字符串。因此,当我尝试在浏览器中点击此 url 'api/values/jjhjh' 时,我收到此错误:

The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.String Get(Int32)' in 'stackOverflowWebApi.Controllers.ValuesController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.

【问题讨论】:

  • 你能说明你是如何尝试传递字符串的吗?
  • 你试过让 id 可以为空吗?
  • 您显示的路线是Routeconfig,您能告诉我们您的WebApiconfig
  • 你的自定义路由是放在RouteConfig中的默认路由之前还是之后?
  • 为什么你有第二个默认路由和第一个默认路由做同样的事情?那不会做任何事情。我建议使用路由调试器对您必须查看的路由进行故障排除,看看它失败的原因。请参阅 Phil Hackk 关于 Route 调试器的博客。

标签: asp.net asp.net-mvc-4 c#-4.0 asp.net-mvc-routing


【解决方案1】:

您添加的附加路由是 MVC 路由,而不是 WebAPI 路由。 WebAPI 路由默认不在 RouteConfig.cs 中,它们在 WebApiConfig.cs 中。它们看起来更像这样:

config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

您发布的错误来自根本没有传递任何数据。试试这个吧:

public string Get(string id = null)
{
    return "othervalue";
}

请注意,参数名称是id,而不是arg,以使其匹配可选的路由参数。此外,将其默认为 null 会告诉 binder,在没有数据传递时可以调用此方法。

【讨论】:

    猜你喜欢
    • 2018-08-03
    • 2021-09-30
    • 1970-01-01
    • 2014-12-11
    • 2021-11-18
    • 1970-01-01
    • 1970-01-01
    • 2016-02-14
    • 2023-03-14
    相关资源
    最近更新 更多