簡體   English   中英

ASP.Net Core Put FromBody 請求驗證 - json 請求僅包含一個 bool 字段

[英]ASP.Net Core Put FromBody request validation - json request contains only one bool field

我必須確保為 PUT 端點提交的請求包含一個也是唯一一個 bool 類型的元素。 請求采用 Json 格式,如下所示,可能值為真或假。

{
   "canRegister": true
}

下面是C#請求object和Controller中對應的方法(端點)。 公共 class 注冊請求查看模型

{
    [Required]
    [JsonPropertyName("canRegister")]
    [JsonProperty(Required = Required.Always)]
    [Range(typeof(bool), "false", "true", ErrorMessage = "false or true are only allowed values")]
    public bool CanRegister { get; set; }
}

public IActionResult Put([FromBody]RegistrationRequestViewModel request)

雖然當請求包含“canRegister”時這完全符合我的預期,但我面臨的問題是當請求不包含“canRegister”時,C# 的默認序列化仍然導致請求 object 包含“canRegister”且為 false價值。

誰能告訴我如何確保這個不正確的 Json 轉換不會發生? 我嘗試使用自定義 ActionFilter 並意識到在調用 OnActionExecuting 方法時發生了不正確的轉換。

[JsonProperty(Required = Required.Always)]在Json.Net中使用。自Z1848E732214CCE460F9B24F0C80F5073E核心共享框架ASP.NET核心共享框架中移除。

為了滿足您的要求,您可以添加 NewtonSoft 支持:

1.安裝Microsoft.AspNetCore.Mvc.NewtonsoftJson package。

2.更新Startup.ConfigureServices以調用AddNewtonsoftJson

services.AddControllers()
    .AddNewtonsoftJson();

3.更新您的 model:

public class RegistrationRequestViewModel
{
    [Required]
    //[JsonPropertyName("canRegister")]
    [Newtonsoft.Json.JsonProperty(Required = Newtonsoft.Json.Required.Always,PropertyName = "canRegister")]
    [Range(typeof(bool), "false", "true", ErrorMessage = "false or true are only allowed values")]
    public bool CanRegister { get; set; }
    public string Title { get; set; }
}

結果:

在此處輸入圖像描述

如果您仍想使用System.Text.Json ,您可以自定義 JsonConverter:

public class RegistrationRequestViewModelJsonConverter : JsonConverter<RegistrationRequestViewModel>
{
    public override bool CanConvert(Type typeToConvert)
    {
        return base.CanConvert(typeToConvert);
    }
    public override RegistrationRequestViewModel Read(
        ref Utf8JsonReader reader,
        Type typeToConvert,
        JsonSerializerOptions options)
    {
        var flag = false;
        var model = new RegistrationRequestViewModel();
        List<string> list = new List<string>();

        while (reader.Read())
        {
            if (reader.TokenType == JsonTokenType.PropertyName)
            {
                string propertyName = reader.GetString();
                list.Add(propertyName);
                reader.Read();
                switch (propertyName)
                {
                    //canRegister and title is the key name you post in json
                    case "canRegister":
                        bool canRegister = reader.GetBoolean();
                        model.CanRegister = canRegister;
                        flag = true;
                        break;
                    case "title":
                        string title = reader.GetString();
                        model.Title = title;
                        flag = true;
                        break;
                }                   
            }
        }
        if (!list.Contains("canRegister"))
        {
            throw new JsonException("CanRegister field must be provided");
        }
        return model;           
    }

    public override void Write(
        Utf8JsonWriter writer,
        RegistrationRequestViewModel value,
        JsonSerializerOptions options)
    {
        writer.WriteStringValue(value.ToString());
    }
}

Model:

[JsonConverter(typeof(RegistrationRequestViewModelJsonConverter))]
public class RegistrationRequestViewModel
{
    [Required]
    [JsonPropertyName("canRegister")]
    // [JsonProperty(Required = Required.Always)]
    [Range(typeof(bool), "false", "true", ErrorMessage = "false or true are only allowed values")]
    public bool CanRegister { get; set; }
    public string Title { get; set; }
}

結果:

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM