简体   繁体   English

在Web API中获取请求为null?

[英]get request in web api null?

I just started using web api and I was wondering if the parameter value is supposed to be null if you don't have any query parameters. 我刚刚开始使用Web api,我想知道如果您没有任何查询参数,参数值是否应该为null

For example, I have this model: 例如,我有这个模型:

[DataContract]
public class GetBooksRequest
{
    public int? BookLimit { get; set; }
}

Used in the following action 用于以下动作

[HttpGet]
[Route("api/books")]
public IHttpActionResult Get([FromUri]GetBooksRequest request) {
  // request is null
}

Is parameter value supposed to be null if I hit api/books ?. 如果我点击api/books参数值应该为null吗?

It hits my endpoint, but parameter is null . 它到达了我的端点,但参数为null If I do api/books?booklimit=1 , then parameter is not null and the BookLimit property is set to 1 as expected. 如果我执行api/books?booklimit=1 ,则参数不为null ,并且BookLimit属性按预期设置为1

I just wasn't sure if that's the way web api works. 我只是不确定这是否是Web api的工作方式。

Yes that is how it works. 是的,这就是它的工作原理。 The framework inspects the request and will build up the model from the URI (because it was told to check by [FromUri] attribute) . 框架检查请求并从URI建立模型(因为[FromUri]属性告诉它检查)

If it cannot build the model with the provided information the model/parameter will be set to its default value, in this case null . 如果无法使用提供的信息构建模型,则模型/参数将设置为其默认值,在这种情况下为null That is by design. 那是设计使然。

Source: Parameter Binding in ASP.NET Web API 来源: ASP.NET Web API中的参数绑定

Using [FromUri] 使用[FromUri]

To force Web API to read a complex type from the URI, add the [FromUri] attribute to the parameter. 要强制Web API从URI读取复杂类型,请将[FromUri]属性添加到参数中。 The following example defines a GeoPoint type, along with a controller method that gets the GeoPoint from the URI. 以下示例定义了GeoPoint类型以及从URI获取GeoPoint的控制器方法。

 public class GeoPoint { public double Latitude { get; set; } public double Longitude { get; set; } } public ValuesController : ApiController { public HttpResponseMessage Get([FromUri] GeoPoint location) { ... } } 

The client can put the Latitude and Longitude values in the query string and Web API will use them to construct a GeoPoint. 客户端可以将纬度和经度值放入查询字符串中,Web API将使用它们来构造GeoPoint。 For example: 例如:

 http://localhost/api/values/?Latitude=47.678558&Longitude=-122.130989 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM