[英]How do you enforce required query string parameters in Web API 2?
给定使用[FromUri]的示例:
public class GeoPoint
{
public double Latitude { get; set; }
public double Longitude { get; set; }
}
public ValuesController : ApiController
{
public HttpResponseMessage Get([FromUri] GeoPoint location) { ... }
}
http://localhost/api/values/
和http://localhost/api/values/?Latitude=47.678558&Longitude=-122.130989
都将在当前实现中将Latitude
和Longitude
都设置为0,但是我想区分两者因此,如果未提供这些错误,则会抛出400错误。
如果未提供“ Latitude
或“ Longitude
是否可以拒绝请求?
您可以重载此操作:
[HttpGet]
public HttpResponseMessage Get([FromUri] GeoPoint location) { ... }
[HttpGet]
public HttpResponseMessage Get() {
throw new Exception("404'd");
...
}
或者,您可以使您的类成员可以为空,并进行空检查:
public class GeoPoint
{
public double? Latitude { get; set; }
public double? Longitude { get; set; }
}
public ValuesController : ApiController
{
public HttpResponseMessage Get([FromUri] GeoPoint location)
{
if(location == null || location.Longitude == null || location.Latitude == null)
throw new Exception("404'd");
}
}
我这样做了,最终看起来像@mambrow的第二个选项,只是其余的代码不必处理可空类型:
public class GeoPoint
{
private double? _latitude;
private double? _longitude;
public double Latitude {
get { return _latitude ?? 0; }
set { _latitude = value; }
}
public double Longitude {
get { return _longitude ?? 0; }
set { _longitude = value; }
}
public bool IsValid()
{
return ( _latitude != null && _longitude != null )
}
public ValuesController : ApiController
{
public HttpResponseMessage Get([FromUri] GeoPoint location)
{
if ( !location.IsValid() ) { throw ... }
...
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.