为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

C#
心有法竹 2022-08-20 16:56:19
我有一个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!这似乎是设计使然,但是有没有办法将空字符串视为空字符串?
查看完整描述

2 回答

?
ITMISS

TA贡献1871条经验 获得超8个赞

在 HTML 中没有空值这样的东西。输入具有某个值或空值。甚至没有办法通过查看查询参数来判断值是字符串还是数字。

HTML 表单的默认行为是在提交时包含所有字段。因此,即使输入没有值,它仍将作为查询的一部分包含在内。 并且都是表示没有为字段输入值的有效语法。www.example.com/xxx?str=www.example.com/xxxstr

但是,您可以包括隐藏字段

<input name="IsEmptyString" type="hidden"/>

,然后使用 JavaScript 根据用于确定它是空还是空的任何逻辑来设置值。


查看完整回答
反对 回复 2022-08-20
?
明月笑刀无情

TA贡献1828条经验 获得超4个赞

我发现了这个很棒的解决方案,从 https://stackoverflow.com/a/35966463/505893 复制并进行了改进。它是 Web 应用的全局配置中的自定义项。


public static class WebApiConfig

{

    public static void Register(HttpConfiguration config)

    {

        //treat query string parameters of type string, 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

        //see https://stackoverflow.com/q/54484640/505893

        GlobalConfiguration.Configuration.BindParameter(typeof(string), new EmptyStringModelBinder());


        //...

    }

}


/// <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

{

    public bool BindModel(HttpActionContext actionContext, System.Web.Http.ModelBinding.ModelBindingContext bindingContext)

    {

        var vpr = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);

        if (vpr != null)

        {

            //parameter has been passed

            //preserve its value!

            //(if empty string, leave it as it is, instead of setting null)

            bindingContext.Model = vpr.AttemptedValue;

        }


        return true;

    }

}


查看完整回答
反对 回复 2022-08-20
  • 2 回答
  • 0 关注
  • 223 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号