亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

防止 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 關注
  • 206 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號