鉴于Using [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
,是否可以拒绝该请求?
答案 0 :(得分:1)
您可以重载此操作:
[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");
}
}
答案 1 :(得分:-1)
我做了这个,最终看起来像@ 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 ... }
...
}
}