Last active
May 5, 2016 16:29
-
-
Save Ciantic/d1cd2f0680e50acd512b479872bb5e3b to your computer and use it in GitHub Desktop.
Request user attribute, helper for identity
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.Threading.Tasks; | |
| using AspNetApiMonolithSample.Models; | |
| using Microsoft.AspNetCore.Identity; | |
| using Microsoft.AspNetCore.Mvc.ModelBinding; | |
| namespace AspNetApiMonolithSample.Mvc | |
| { | |
| /// <summary> | |
| /// Request user modelbinder from UserManager automatically | |
| /// </summary> | |
| public class RequestUserModelBinder : IModelBinder | |
| { | |
| private readonly UserManager<User> _userManager; | |
| public RequestUserModelBinder(UserManager<User> userManager) | |
| { | |
| _userManager = userManager; | |
| } | |
| public async Task BindModelAsync(ModelBindingContext bindingContext) | |
| { | |
| var user = await _userManager.GetUserAsync(bindingContext.OperationBindingContext.ActionContext.HttpContext.User); | |
| bindingContext.Result = ModelBindingResult.Success(bindingContext.ModelName, user); | |
| } | |
| } | |
| /// <summary> | |
| /// Get the request user from UserManager automatically | |
| /// </summary> | |
| [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Property, AllowMultiple = true, Inherited = true)] | |
| public class RequestUserAttribute : Attribute, IBinderTypeProviderMetadata | |
| { | |
| public BindingSource BindingSource | |
| { | |
| get | |
| { | |
| return new BindingSource( | |
| id: "RequestUser", | |
| displayName: "RequestUser", | |
| isGreedy: false, | |
| isFromRequest: false); // isFromRequest has to be false so it is ignored in Swagger UI | |
| } | |
| } | |
| Type IBinderTypeProviderMetadata.BinderType | |
| { | |
| get | |
| { | |
| return typeof(RequestUserModelBinder); | |
| } | |
| } | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I hereby place this to public domain.