您如何在 Web API 2 中执行必需的查询字符串参数?

How do you enforce required query string parameters in Web API 2?

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 都会将 LatitudeLongitude 都设置为 0 当前的实现,但我想区分两者以便我可以抛出如果未提供,则会出现 400 错误。

没有提供LatitudeLongitude是否可以拒绝请求?

您可以重载此操作:

[HttpGet]
    public HttpResponseMessage Get([FromUri] GeoPoint location) { ... }

[HttpGet]
public HttpResponseMessage Get() { 
    throw new Exception("404'd");
    ...
 }

或者您可以让您的 class 成员可以为空并进行空检查:

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 ... }
        ...
    }
}