如何在Web API 2中强制执行所需的查询字符串参数?

时间:2015-03-11 20:56:41

标签: c# asp.net asp.net-web-api2

鉴于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,是否可以拒绝该请求?

2 个答案:

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