网页API模型验证和默认值 [英] Web API model validation and default values

查看:84
本文介绍了网页API模型验证和默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是精神的继承我的previous问题<一href=\"http://stackoverflow.com/questions/30468805/web-api-attribute-routing-and-validation-possible\">Web API属性路由和验证 - 可能,我认为这是过于笼统回答。大多数的这些问题都解决了,但仍然是默认值的问题。

This is the spiritual successor to my previous question Web API attribute routing and validation - possible?, which I think was too general to answer. Most of those issues are solved, but the default value question remains.

基本上我已经解决了这个难题多件。我有这样的:

Basically I have solved many pieces of the puzzle. I have this:

[HttpGet]
[Route("test/{id}"]
public IHttpActionResult RunTest([FromUri]TestRequest request)
{
    if (!ModelState.IsValid) return BadRequest(ModelState);
    return Ok();
}

我的 TestRequest 类:

public class TestRequest
{
    public string id { get; set; }

    [DefaultValue("SomethingDefault")]
    public string something { get; set; }
}

问题是,如果不带参数的查询字符串的东西,该模型是有效,但的东西

The problem is that if no parameter is in the query string for something, the model is "valid" and yet something is null.

如果我指定的东西(即获取测试/ 123?东西= ),那么一个空值默认值进场时,该模型是有效的一次。

If I specify a blank value for something (i.e. GET test/123?something=), then the default value comes into play, and the model is valid again.

这是为什么?我怎样才能得到一个默认值到我这里的模型?作为奖励,为什么不指定参数时,默认值是不使用的,但是当一个空字符串是明确具体的,则使用默认值?

Why is this? How can I get a default value into my model here? As a bonus, why is it when a parameter is not specified, the default value is not used, but when a blank string is explicitly specific, the default value is used?

(我一直拖网通过ASP.NET栈源$ C ​​$ c和我没膝深的模型粘合剂和结合上下文但我最好的猜测不可能是正确的 - 它看起来像 DefaultValueAttribute 仅用于当参数值为,但这里并非如此)

(I've been trawling through the ASP.NET stack source code and am knee-deep in model binders and binding contexts. But my best guess can't be right - it looks like the DefaultValueAttribute is used only if the parameter value is null. But that's not the case here)

推荐答案

在构造函数中指定默认的工作时,都没有指定参数,但是当指定了一个空字符串,投入现场来代替。

Specifying the default in the constructor works for when no parameter is specified at all, but when a blank string is specified, null is put into the field instead.

因此​​,加入 [默认值()] 实际工作中最好的 - 被指定了一个空字符串时,一个空字符串传递在随后的构造函数可以。该参数丢失时的缺省值。

As such, adding [DefaultValue("")] actually worked the best - when a blank string was specified, a blank string was passed in. Then the constructor can specify default values for when the parameter is missing.

要解决这个问题,我创建 preserveBlankStringAttribute ,从 DefaultValueAttribute 派生相当于 [默认值()]

To get around this, I've created PreserveBlankStringAttribute, derives from DefaultValueAttribute which is equivalent to [DefaultValue("")].

我会非常欢迎比这更好的答案,请。

I would very much welcome a better answer than this, please.

这篇关于网页API模型验证和默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆