簡體   English   中英

在 ASP.NET Core 3.x 中使用 [FromRoute] 綁定到復雜的 object 給出 null

[英]Bind to complex object using [FromRoute] in ASP.NET Core 3.x gives null

我有一個簡單的 controller,它允許路由路徑受“復雜對象”中的正則表達式模式約束。 當我嘗試從 object 讀取單個屬性時,它始終是 null。

ModelState顯示錯誤集合說:

ActorId 字段是必需的

所以它似乎是一個 model 綁定問題而不是驗證問題。

我覺得我在[HttpGet]塊或其他東西中缺少模式。

ActorIdParameter.cs

public sealed class ActorIdParameter
{
    [Required]
    [RegularExpression(@"^.*nm(\d{5}|\d{7})$")]
    public string ActorId { get; set; }
}

ActorsController.cs

[HttpGet("{actorIdParameter}")]
public async Task<IActionResult> GetActorByIdAsync([FromRoute]ActorIdParameter actorIdParameter)
{
    _ = actorIdParameter ?? throw new ArgumentNullException(nameof(actorIdParameter));
        
    // validation result
    if (!ModelState.IsValid) //<---this is always false
        return ValidationProcessor.GetAndLogInvalidActorIdParameter(method, logger);
}

使用此示例調用代碼:http://localhost:4120/api/actors/nm0000206

還有其他幾篇文章涉及[FromQuery][FromBody] ,但我找不到任何涉及路由路徑的文章。 似乎{actorIdParameter}需要說“獲取該對象中的 ActorId 屬性”之類的話。

我覺得我需要復雜的 object 來進行正則表達式匹配。 或者,我可以從ActorIdParameter object 切換到一個string ,並可能在GetActorByIdAsync方法上內聯裝飾它,但我很好奇是否有人有任何建議?

下面的代碼適用於我使用

https://localhost:5001/api/actors/nm0000206

並且驗證正確地失敗了

https://localhost:5001/api/actors/42

您不需要為此進行任何自定義處理。

public class ActorIdParameter
{
    [Required]
    [RegularExpression(@"^.*nm(\d{5}|\d{7})$")]
    [FromRoute]
    public string ActorId { get; set; }
}

[Route("api/actors")]
public class ActorsController : ControllerBase
{
    [HttpGet("{actorId}")]
    public async Task<IActionResult> GetActorByIdAsync(ActorIdParameter model)
    {
        if (!ModelState.IsValid)
        {
            return new BadRequestResult();
        }

        return new OkResult();
    }
}
  1. 嘗試對這三個進行 GET 請求,將actors更改為您的 controller 路由:
  • http://url/actors/nm11111
  • http://url/actors?actorIdParameter=nm11111
  • http://url/actors/?actorIdParameter=nm11111

有沒有工作?

檢查你 model 錯誤(了解為什么它是錯誤的):

var errors = ModelState
    .Where(x => x.Value.Errors.Count > 0)
    .Select(x => new { x.Key, x.Value.Errors })
    .ToArray();

ModelState.IsValid == false,為什么?

暫無
暫無

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

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