首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >添加用于响应处理的属性

添加用于响应处理的属性
EN

Stack Overflow用户
提问于 2020-10-01 15:45:08
回答 1查看 298关注 0票数 1

使用C#,NetCore3.1

我想知道是否有人能帮忙。我想添加“中间件”,但我认为我的需求需要一个属性,因为我只想对特定的API操作有选择地这样做。如何在响应发送到请求客户端之前对响应进行某些处理(例如签名消息并将其添加到响应头)?

例如

代码语言:javascript
运行
复制
    [HttpGet]
    [PostResponseProcessAttribute]
    public IActionResult GetFoo(int id) {
        return MyFoo();
    }

所以对于这个GetFoo动作,我想做这样的事情:

代码语言:javascript
运行
复制
public class PostResponseProcessAttribute : Attribute {
    public OnBeforeSendingResponse(){
      var response = Response.Content.ReadAsStringAsync;
     //do some stuff
      response.Headers.Add(results from stuff)
    }
}

它是我需要实现的属性吗?我需要重写的函数是什么?另外,关键的一点是,响应的格式和状态将发送给客户端(即传递给其他格式化中间件处理等)--这对于签名非常重要,因为任何差异都意味着客户端正在验证不同版本的响应,因此总是失败。

谢谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-10-01 16:35:32

最后,我写到:

代码语言:javascript
运行
复制
public sealed class AddHeadersRequiredAttribute : Attribute
{
}

public class AddHeadersMiddleware
{
    private readonly RequestDelegate _next;

    public AddHeadersMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        await using var memory = new MemoryStream();
        var originalStream = context.Response.Body;
        context.Response.Body = memory;

        await _next(context);

        memory.Seek(0, SeekOrigin.Begin);
        var content = await new StreamReader(memory).ReadToEndAsync();
        memory.Seek(0, SeekOrigin.Begin);

        // Now you can manipulate with content
        var attribute = GetAddHeadersRequiredAttributeFromMatchedAction(context);
        if (attribute != null)
            context.Response.Headers.Add("X-Header-1", content);

        await memory.CopyToAsync(originalStream);
        context.Response.Body = originalStream;
    }

    private Attribute GetAddHeadersRequiredAttributeFromMatchedAction(HttpContext context)
    {
        var endpoint = context.GetEndpoint();
        var controllerActionDescriptor = endpoint?.Metadata.GetMetadata<ControllerActionDescriptor>();
        return controllerActionDescriptor?.MethodInfo.GetCustomAttribute<AddHeadersRequiredAttribute>();
    }
}

您可以使用AddHeadersRequiredAttribute标记控制器方法。然后在Startup.Configure方法中使用中间件,如下所示

代码语言:javascript
运行
复制
app.UseMiddleware<AddHeadersMiddleware>();
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64158823

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档