use*_*135 3 c# json.net asp.net-core-webapi
我希望OkObjectResult通过我拥有的自定义 JSON 解析器运行来自 api 的所有响应。解析器依赖于一些特定于请求的数据——即用户的角色。它实际上类似于控制器上的 Authorize 属性,但用于从 API 传递到 UI 的数据传输对象。
我可以通过 AddJsonOptions 在配置服务中添加解析器,但它无权访问那里的用户信息。
如何将基于请求的值传递给该解析器?我是在寻找某种自定义中间件,还是其他什么?
作为示例,如果我有一个带有一些自定义属性装饰器的对象,如下所示:
public class TestObject
{
public String Field1 => "NoRestrictions";
[RequireRoleView("Admin")]
public String Field2 => "ViewRequiresAdmin";
}
Run Code Online (Sandbox Code Playgroud)
并使用不同的角色调用我的自定义序列化器,如下所示:
var test = new TestObject();
var userRoles = GetRoles(); // "User" for the sake of this example
var outputJson = JsonConvert.SerializeObject(test,
new JsonSerializerSettings {
ContractResolver = new MyCustomResolver(userRoles)
});
Run Code Online (Sandbox Code Playgroud)
然后输出 JSON 将跳过用户无法访问的任何内容,如下所示:
{
"Field1":"NoRestrictions",
// Note the absence of Field2, since it has [RequireRoleView("Admin")]
}
Run Code Online (Sandbox Code Playgroud)
假设您有一个自定义RequireRoleViewAttribute:
[AttributeUsageAttribute(AttributeTargets.All, Inherited = true, AllowMultiple = true)]
public class RequireRoleViewAttribute : Attribute
{
public string Role;
public RequireRoleViewAttribute(string role){
this.Role = role;
}
}
Run Code Online (Sandbox Code Playgroud)
如何将基于请求的值传递给该解析器?
您可以IServiceProvider在自定义解析器中注入:
public class RoleBasedContractResolver : DefaultContractResolver
{
public IServiceProvider ServiceProvider { get; }
public RoleBasedContractResolver( IServiceProvider sp)
{
this.ServiceProvider = sp;
}
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
var contextAccessor = this.ServiceProvider.GetRequiredService<IHttpContextAccessor>() ;
var context = contextAccessor.HttpContext;
var user = context.User;
// if you're using the Identity, you can get the userManager :
var userManager = context.RequestServices.GetRequiredService<UserManager<IdentityUser>>();
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
这样我们就可以得到我们想要的HttpContext和。User如果您使用身份,您还可以获得UserManager服务和角色。
现在我们可以按照@dbc的建议来控制ShouldSerialize:
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
var contextAccessor = this.ServiceProvider.GetRequiredService<IHttpContextAccessor>() ;
var context = contextAccessor.HttpContext;
var user = context.User;
// if you use the Identitiy, you can get the usermanager
//UserManager<IdentityUser>
var userManager = context.RequestServices.GetRequiredService<UserManager<IdentityUser>>();
JsonProperty property = base.CreateProperty(member, memberSerialization);
// get the attributes
var attrs=member.GetCustomAttributes<RequireRoleViewAttribute>();
// if no [RequireResoveView] decorated, always serialize it
if(attrs.Count()==0) {
property.ShouldDeserialize = instance => true;
return property;
}
// custom your logic to dertermine wether should serialize the property
// I just use check if it can statisify any the condition :
var roles = this.GetIdentityUserRolesAsync(context,userManager).Result;
property.ShouldSerialize = instance => {
var resource = new { /* any you need */ };
return attrs.Any(attr => {
var rolename = attr.Role;
return roles.Any(r => r == rolename ) ;
}) ? true : false;
};
return property;
}
Run Code Online (Sandbox Code Playgroud)
这里的函数GetIdentityUserRolesAsync是使用当前HttpContext和UserManger服务检索角色的辅助方法:
private async Task<IList<string>> GetIdentityUserRolesAsync(HttpContext context, UserManager<IdentityUser> userManager)
{
var rolesCached= context.Items["__userRoles__"];
if( rolesCached != null){
return (IList<string>) rolesCached;
}
var identityUser = await userManager.GetUserAsync(context.User);
var roles = await userManager.GetRolesAsync(identityUser);
context.Items["__userRoles__"] = roles;
return roles;
}
Run Code Online (Sandbox Code Playgroud)
如何注入的IServiceProvider详细信息:
诀窍在于如何MvcJwtOptions使用IServiceProvider.
不要配置JsonOptionsby :
services.AddMvc().
.AddJsonOptions(o =>{
// o.
});
Run Code Online (Sandbox Code Playgroud)
因为它不允许我们添加IServiceProvider参数。
我们可以自定义一个子类MvcJsonOptions:
// in .NET 3.1 and above, change this from MvcJsonOptions to MvcNewtonsoftJsonOptions
public class MyMvcJsonOptionsWrapper : IConfigureOptions<MvcJsonOptions>
{
IServiceProvider ServiceProvider;
public MyMvcJsonOptionsWrapper(IServiceProvider serviceProvider)
{
this.ServiceProvider = serviceProvider;
}
public void Configure(MvcJsonOptions options)
{
options.SerializerSettings.ContractResolver =new RoleBasedContractResolver(ServiceProvider);
}
}
Run Code Online (Sandbox Code Playgroud)
并通过以下方式注册服务:
services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
// don't forget to add the IHttpContextAccessor
// in .NET 3.1 and above, change this from MvcJsonOptions to MvcNewtonsoftJsonOptions
services.AddTransient<IConfigureOptions<MvcJsonOptions>,MyMvcJsonOptionsWrapper>();
Run Code Online (Sandbox Code Playgroud)
测试用例 :
假设您有一个自定义 POCO :
public class TestObject
{
public string Field1 => "NoRestrictions";
[RequireRoleView("Admin")]
public string Field2 => "ViewRequiresAdmin";
[RequireRoleView("HR"),RequireRoleView("OP")]
public string Field3 => "ViewRequiresHROrOP";
[RequireRoleView("IT"), RequireRoleView("HR")]
public string Field4 => "ViewRequiresITOrHR";
[RequireRoleView("IT"), RequireRoleView("OP")]
public string Field5 => "ViewRequiresITOrOP";
}
Run Code Online (Sandbox Code Playgroud)
当前用户具有以下角色 :Admin和HR:
结果将是:
{"Field1":"NoRestrictions","Field2":"ViewRequiresAdmin","Field3":"ViewRequiresHROrOP","Field4":"ViewRequiresITOrHR"}
Run Code Online (Sandbox Code Playgroud)
使用操作方法进行测试的屏幕截图: