【问题标题】:Access attribute from outside of a controller从控制器外部访问属性
【发布时间】:2020-01-27 12:05:55
【问题描述】:

是否可以从控制器外部访问控制器操作的自定义属性?我有一个自定义输出格式化程序,它应该返回一个具有特定名称的文件。我创建了一个接受字符串(文件名)的自定义属性,我想尝试从自定义输出格式化程序中访问该属性的值。

public class FileAttribute : Attribute
{
public ExcelTemplateAttribute(string fileName)
{
    FileName = fileName;
}

    public string FileName { get; }
}

我的OutputFormatter 看起来像这样:

public class FileOutputFormatter : OutputFormatter
{
    public override Task WriteResponseBodyAsync(OutputFormatterWriteContext context) 
    {
        // string filename = ???
    }
}

我的 API 操作返回一个服务

[File("Template.txt")]
public IActionResult Get([FromQuery]int Id)
{
    IEnumerable<int> data = _kenoReport.GetReportData(Id);

    return Ok(data);
}

【问题讨论】:

    标签: api asp.net-core .net-core formatting asp.net-core-webapi


    【解决方案1】:

    在中间件管道的 MVC 特定部分之外,如果不借助依赖于反射的复杂(且易于破解)的代码,就不容易访问控制器和/或操作信息。

    但是,一种解决方法是使用操作过滤器将属性详细信息添加到 HttpContext.Items 字典(可在整个中间件管道中访问),并让输出格式化程序稍后在中间件管道中检索它。

    例如,您可以让您的 FileAttribute 派生自 ActionFilterAttribute,并在执行时将其添加到 HttpContext.Items(使用唯一的对象引用作为键):

    public sealed class FileAttribute : ActionFilterAttribute
    {
        public FileAttribute(string filename)
        {
            Filename = filename;
        }
    
        public static object HttpContextItemKey { get; } = new object();
    
        public string Filename { get; }
    
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            context.HttpContext.Items[HttpContextItemKey] = this;
        }
    }
    

    然后在您的输出格式化程序中,您可以检索属性实例并访问文件名:

    public sealed class FileOutputFormatter : OutputFormatter
    {
        public override async Task WriteResponseBodyAsync(OutputFormatterWriteContext context)
        {
            if (context.HttpContext.Items.TryGetValue(FileAttribute.HttpContextItemKey, out var item)
                && item is FileAttribute attribute)
            {
                var filename = attribute.Filename;
    
                // ...
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2013-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-17
      • 2017-03-13
      相关资源
      最近更新 更多