简体   繁体   English

具有用户名的模型绑定Asp.Net Core

[英]Model Binding Asp.Net Core with username

Currently I have a generic method in my Web API that takes in a collection and stores it into the database. 当前,我的Web API中有一个通用方法,该方法接受一个集合并将其存储到数据库中。 I'm adding the username by looping through the entire collection again and adding the username. 我通过再次遍历整个集合并添加用户名来添加用户名。

I feel like this is inefficient and I would like to write something generic so that I can add the username at the time of model binding or when I'm using automapper. 我觉得这效率很低,我想写一些通用的东西,以便在模型绑定时或使用自动映射器时可以添加用户名。 I wonder if there is a more efficient way to do this, than my current approach: 我想知道是否有比我目前的方法更有效的方法:

[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 does have support for defining mapping actions in ASP.NET Core . AutoMapper确实支持在ASP.NET Core中定义映射操作 You could likely configure that as shown there and use something like the following for the Process method of the IMappingAction<> implementation: 您可能会如此处所示进行配置,并对IMappingAction<>实现的Process方法使用类似以下的内容:

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

I'd caution that this might be premature optimization though. 我警告这可能是过早的优化。 This is a nice solution for ensuring that something happens consistently on every map in the same way. 这是一个很好的解决方案,可确保以相同方式在每张地图上一致地进行操作。 But it may also serve to make the code less readable to someone coming later on, so just be aware of that. 但这也可能使以后的代码难以理解,因此请注意这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM