Skip to content

Instantly share code, notes, and snippets.

@Ciantic
Last active May 5, 2016 16:29
Show Gist options
  • Select an option

  • Save Ciantic/d1cd2f0680e50acd512b479872bb5e3b to your computer and use it in GitHub Desktop.

Select an option

Save Ciantic/d1cd2f0680e50acd512b479872bb5e3b to your computer and use it in GitHub Desktop.
Request user attribute, helper for identity
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);
}
}
}
}
@Ciantic
Copy link
Author

Ciantic commented May 5, 2016

I hereby place this to public domain.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment