简体   繁体   中英

Asp.Net Core Identity async Overhead in Custom Stores

While developing a Asp.Net Core Web Application I needed to add Asp.Net Core Identity to my Project. However I needed only a small part of Identity because eg I know that this application will never allow third party logins. Therefore I decided to write my custom stores. While Searching the Internet for good Solutions on how to do that I often saw a Implementation like this:

    public Task SetUserNameAsync(ApplicationUser user, string userName, CancellationToken cancellationToken)
    {
        cancellationToken.ThrowIfCancellationRequested();

        if (user == null)
            throw new ArgumentNullException(nameof(user));

        if(string.IsNullOrWhiteSpace(userName))
            throw new ArgumentNullException(nameof(userName));

        user.Username = userName;

        return Task.CompletedTask;
    }

or

    public Task<string> GetUserNameAsync(ApplicationUser user, CancellationToken cancellationToken)
    {
        cancellationToken.ThrowIfCancellationRequested();

        if (user == null)
            throw new ArgumentNullException(nameof(user));

        return Task.FromResult(user.Username);
    }

as far as I understand It that would be called in a fashion like this:

var user = await store.GetUserNameAsync(_user, CancellationToken.None);

but wouldn't that basically create a State Mashine for a getter/setter that should just immediately return without any big overhead or is there any good benefit doing it like this that I am not seeing right now?

Identity is a framework that is highly customizable. Eg you could create your own UserManager while still using the standard SignInManager that handles login, logout, ...

What you found seems to be implementations of UserManager.GetUserNameAsync()> https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.identity.usermanager-1.getusernameasync?view=aspnetcore-2.1

The reason why this method returns a task is, that the implementation could required db or network access.

If you really don't want to use anything of Identity and do everyting yourself, there's no need to return a task. But to be hornest, I'd suggest to think twice if this is a good approach.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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