gpt4 book ai didi

c# - 生成由操作过滤器控制的 PDF?

转载 作者:行者123 更新时间:2023-11-30 18:25:53 25 4
gpt4 key购买 nike

当客户端在 Web API 路由的查询字符串中传递特定参数 (?print) 时,我需要生成特定数据集的 PDF 报告。现在我想知道自定义操作过滤器是否适合执行此操作。

public class ReportFilterAttribute : ActionFilterAttribute {

public ReportFilterAttribute(string controller, string layoutPath) {

}

public override void OnActionExecuting(HttpActionContext actionContext)
{
// look for parameter ?print in the request query string
}

public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
// load layout file
// fill in data returned by the api
// manipulate response to return a filestream instead of json data
}
}
  1. 有没有办法阻止 OnActionExecuted 被调用,例如当没有参数 ?print available?
  2. 根据请求返回文件流 (PDF) 或 JSON 数据是否是可接受的做法(客户应如何知道这一点?)
  3. 是否可以使用 Action 过滤器来执行此操作,或者我应该更好地编写例如自定义 OWIN 中间件?

最佳答案

实现此目的的良好做法是创建自定义 http handler/owin 中间件。最好为不同类型的响应使用不同的处理程序/中间件,而不是代码中某处的“隐藏逻辑”。

您有一个默认返回 JSON 数据的 WebApi,但在某些情况下它会返回 PDF 文件。对我来说这听起来很奇怪。使用 http 处理程序,您将不会有描述一些模糊逻辑的注释,例如:

// look for parameter ?print in the request query string
// manipulate response to return a filestream instead of json data

这两个组件的名称描述了它们自己。HttpHandler 听起来像是它将处理某种请求,而另一方面,ActionFilter 听起来像是将请求过滤为具体操作。

这里引用了 MSDN 中关于操作过滤器的一段话:

Action filter, which wraps the action method execution. This filter can perform additional processing, such as providing extra data to the action method, inspecting the return value, or canceling execution of the action method.

还有一个中间件,你会失去某种代码耦合,让你的代码更容易阅读和维护。但这在很大程度上取决于您的团队约定以及围绕该段代码的所有业务逻辑。

关于c# - 生成由操作过滤器控制的 PDF?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29489693/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com