[英]How to use optional value type (i.e. struct) parameters without using Nullable<T> in WebApi 2?
I want action method with optional parameters of value type, but without using Nullable something like我想要带有值类型可选参数的操作方法,但不使用 Nullable 之类的东西
public string Test2([FromUri] MyKey x = default)
{ ... }
When i call this api with /test2?something=42, it is ok, but when I miss any parameter, it throws error当我用 /test2?something=42 调用这个 api 时,没问题,但是当我错过任何参数时,它会抛出错误
The parameters dictionary contains a null entry for parameter 'x' of non-nullable type 'WebApiTst.Controllers.MyKey' for method 'System.String Test2(WebApiTst.Controllers.MyKey)' in 'WebApiTst.Controllers.TestController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
It is strange, that naming that parameter (with same name) makes things even worse...奇怪的是,命名该参数(具有相同名称)会使事情变得更糟......
I am using WebApi 2 with just config.MapHttpAttributeRoutes()我只使用 config.MapHttpAttributeRoutes() 的 WebApi 2
This is my test controller这是我的测试控制器
public class TestController : ApiController
{
// OK - https://localhost:44302/test2?something=22
// NOK - https://localhost:44302/test2
[Route("test2")]
[HttpGet]
public string Test2([FromUri] MyKey x = default)
{
return "TEST2:" + x;
}
// NOK - https://localhost:44302/test3?something=22
// NOK - https://localhost:44302/test3
[Route("test3")]
[HttpGet]
public string Test3([FromUri(Name = "x")] MyKey x = default)
{
return "TEST3:" + x;
}
}
public struct MyKey
{
public static MyKey Empty { get; } = new MyKey();
public int ID { get; set; }
public override string ToString()
{
return $"[ID={ID}]";
}
}
What is causing this?这是什么原因造成的? How to use value-type optional parameters without using Nullable ?
如何在不使用 Nullable 的情况下使用值类型的可选参数?
[Edited:] I am using ModelBinder, which will deserialize MyKey from string. [编辑:] 我正在使用 ModelBinder,它将从字符串反序列化 MyKey。 I also tried same example in Asp.net core webapi and it works.
我也在 Asp.net core webapi 中尝试了相同的示例,并且它有效。
It is a very bad style to make API with query string.使用查询字符串制作 API 是一种非常糟糕的风格。 MUCH BETTER way is to initiate your MyKey class on creation by default values:
更好的方法是在默认值下在创建时启动 MyKey 类:
public class MyKey
{
public string X {get; set;}
public Property1 {get; set;}
public Property2 {get; set;}
public MyKey()
{
X = "default";
Property1=default1;
Property2=default2;
.....
}
and then you can use the action like this然后你可以使用这样的动作
[Route("Test2/{X?}")]
public string Test2(MyKey myKey )
{
return "TEST2: " + myKey.X;
}
if X is null, myKey.X will still have a default value it got on creation.如果 X 为空,则 myKey.X 仍将具有它在创建时获得的默认值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.