簡體   English   中英

具有用戶名的模型綁定Asp.Net Core

[英]Model Binding Asp.Net Core with username

當前,我的Web API中有一個通用方法,該方法接受一個集合並將其存儲到數據庫中。 我通過再次遍歷整個集合並添加用戶名來添加用戶名。

我覺得這效率很低,我想寫一些通用的東西,以便在模型綁定時或使用自動映射器時可以添加用戶名。 我想知道是否有比我目前的方法更有效的方法:

[HttpPost("collections")]
public async virtual Task<IActionResult> PostCollection([FromBody] IEnumerable<DtoPostType> dtoCollection)
{
    try
    {
        var principal = HttpContext.User.Identity as ClaimsIdentity;
        var entitiesToSave = _mapper.Map<List<T>>(dtoCollection);


        foreach (T item in entitiesToSave)
        {
            if (ModelState.IsValid)
            {
                item.CreatedUser = principal.Name;
                _repo.Create<T>(item);

            }
            else
            {
                return BadRequest(ModelState);
            }
        }

        await _repo.SaveAsync();

        return Ok();
    }

    catch (Exception exp)
    {
        _logger.LogCritical($"There was an issue with mapping for {exp}");
        return BadRequest(exp);
    }
}

AutoMapper確實支持在ASP.NET Core中定義映射操作 您可能會如此處所示進行配置,並對IMappingAction<>實現的Process方法使用類似以下的內容:

public void Process(DtoPostType source, EntityType destination)
{
    destination.CreatedUser = 
        (_httpContextAccessor.HttpContext.User.Identity as ClaimsIdentity)?.Name;
}

我警告這可能是過早的優化。 這是一個很好的解決方案,可確保以相同方式在每張地圖上一致地進行操作。 但這也可能使以后的代碼難以理解,因此請注意這一點。

暫無
暫無

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

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