在ASP.NET MVC CORE过滤器中获取基于当前模型的服务

时间:2016-05-02 13:53:50

标签: asp.net-core

我有以下ASP.NET Core过滤器:

Exception in thread "Thread-1" org.hibernate.HibernateException: Could not obtain transaction-synchronized Session for current thread

如何获取当前模型并请求该模型的服务?

1 个答案:

答案 0 :(得分:1)

你可以这样使用

public class ValidateAttribute : ActionFilterAttribute
{
    public override Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        var model = context.ActionArguments.Values.Where(v => !v.GetType().FullName.StartsWith("System.")).FirstOrDefault();
        //check if model is provided

        var service = context.HttpContext.ApplicationServices.GetService<IService<Model>>()

        //custom logic here

        return base.OnActionExecutionAsync(context, next);
    }
}

public class ValidateAttribute : ActionFilterAttribute
{
    private readonly Type _modelType;

    public MyCustomValidationAttribute(Type modelType)
    {
        _modelType = modelType;
    }

    public override Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        var model = context.ActionArguments.Where(a => a.Value.GetType().IsAssignableFrom(_modelType))
                                           .Select(a => a.Value)
                                           .FirstOrDefault();

        //check if model is provided

        var service = context.HttpContext.ApplicationServices.GetService<IService<Model>>()

        //custom logic here

        return base.OnActionExecutionAsync(context, next);
    }
}

在这种情况下,您需要提供混凝土或基础类型的模型

[Validate(typeof(Model))]