防止 webAPI 2 ASP.NET 将空字符串查询参数视为空

我有一个RESTful Web服务,用 ASP.NET WebAPI 2构建。


我在控制器中有这种方法:


[Route("{DocNum:int}")]

public object Patch(int DocNum, string str = null)

{

    if(str == null)

    {

        //do something when parameter has NOT been passed...

    }

    else

    {

        //do something when parameter has been passed...

    }

}

如果我没有通过,它在方法中是空的。str


如果我通过,它在方法中是“abc”。str=abc


如果我传递(空字符串),则它在方法中为空。str=


这就是 WebAPI 2 将空字符串查询参数视为 null ASP.NET!


这似乎是设计使然,但是有没有办法将空字符串视为空字符串?


心有法竹
浏览 224回答 2
2回答

ITMISS

在 HTML 中没有空值这样的东西。输入具有某个值或空值。甚至没有办法通过查看查询参数来判断值是字符串还是数字。HTML 表单的默认行为是在提交时包含所有字段。因此,即使输入没有值,它仍将作为查询的一部分包含在内。 并且都是表示没有为字段输入值的有效语法。www.example.com/xxx?str=www.example.com/xxxstr但是,您可以包括隐藏字段<input&nbsp;name="IsEmptyString"&nbsp;type="hidden"/>,然后使用 JavaScript 根据用于确定它是空还是空的任何逻辑来设置值。

明月笑刀无情

我发现了这个很棒的解决方案,从 https://stackoverflow.com/a/35966463/505893 复制并进行了改进。它是 Web 应用的全局配置中的自定义项。public static class WebApiConfig{&nbsp; &nbsp; public static void Register(HttpConfiguration config)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; //treat query string parameters of type string, that have an empty string value,&nbsp; &nbsp; &nbsp; &nbsp; //(e.g. http://my/great/url?myparam=) as... empty strings!&nbsp; &nbsp; &nbsp; &nbsp; //and not as null, which is the default behaviour&nbsp; &nbsp; &nbsp; &nbsp; //see https://stackoverflow.com/q/54484640/505893&nbsp; &nbsp; &nbsp; &nbsp; GlobalConfiguration.Configuration.BindParameter(typeof(string), new EmptyStringModelBinder());&nbsp; &nbsp; &nbsp; &nbsp; //...&nbsp; &nbsp; }}/// <summary>/// Model binder that treats query string parameters that have an empty string value/// (e.g. http://my/great/url?myparam=) as... empty strings!/// And not as null, which is the default behaviour./// </summary>public class EmptyStringModelBinder : System.Web.Http.ModelBinding.IModelBinder{&nbsp; &nbsp; public bool BindModel(HttpActionContext actionContext, System.Web.Http.ModelBinding.ModelBindingContext bindingContext)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; var vpr = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);&nbsp; &nbsp; &nbsp; &nbsp; if (vpr != null)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //parameter has been passed&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //preserve its value!&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //(if empty string, leave it as it is, instead of setting null)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; bindingContext.Model = vpr.AttemptedValue;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP