ASP.NET Core - 将自定义属性添加到 HttpRequest

Dev*_*Dev 4 c# middleware asp.net-core

我有一些 ASP.NET 中间件,可以分析传入的请求。根据其中可用的内容HttpRequest,我想添加一个可以在代码中使用的自定义属性。我的问题是,有没有办法添加属性HttpRequest以便我可以在控制器中访问它?例如,在我的 中Controller,我想做这样的事情:

namespace MyWebsite.Controllers
{
  public class MyController : Controller

  public IActionResult Index()
  {
    if (this.Request.MyProperty == null)
    {
      return View("~/Views/NoExist.cshtml");
    }
    return View ("/Views/Index.cshtml");
  }
}
Run Code Online (Sandbox Code Playgroud)

MyProperty表示我想通过自定义中间件注入或添加的自定义属性。这可能吗?如果是这样,怎么办?如果不是,推荐的方法是什么?

谢谢你!

Kin*_*ing 10

实现您想要的目标的传统方式是通过共享一切HttpContext.Items。这样您应该keys自己管理,甚至可以声明您的扩展方法以方便设置和获取值。

然而在这里我想介绍一种request featureasp.net core. 与每个请求关联的功能可以由管道中的不同中间件添加,并且可以由任何中间件(如果可用)使用。这看起来更整洁、更有组织,尽管与旧方式相比可能不太方便。

假设您在中间件的上下文中,以下代码将添加一个公开您的属性的功能:

//declare the feature interface first
public interface IMyFeature {
    string MyProperty {get;}
}

//the concrete type for the feature
public class MyFeature : IMyFeature {
    public MyFeature(string myProperty){
        MyProperty = myProperty;
    }
    public string MyProperty {get;}
}

//the context is in your middleware
//add the feature
var myFeature = new MyFeature("value of your choice");
//context here is the HttpContext
context.Features.Set<IMyFeature>(myFeature);
Run Code Online (Sandbox Code Playgroud)

现在,在管道中的任何位置,您都可以使用添加的功能,如下所示:

//context here is the HttpContext
var myFeature = context.Features.Get<IMyFeature>();
if(myFeature != null){
    //consume your feature
}
Run Code Online (Sandbox Code Playgroud)

我认为这个概念的优点之一request features是其明确的定义,feature interfaces可以通过代码轻松学习、引用和管理。即使将其移植到某个库以进行重用也比依赖某个常量键来访问共享数据(通过使用实现HttpContext.Items)更有意义。当然,对于一些简单的数据共享,您可以只使用HttpContext.Items,请求功能应该在以后发展、有一个清晰的酷概念并且可能包含更多数据时使用。