[ASP.NET] 使用Request 傳遞引數
ASP.NET 的Request 物件的生命週期很短,只會出現在一個Http Request,當需要跨物件傳遞資料時,比如HttpModule、HttpHandler、Page 、Controller,可以善用Request 物件來存放短暫的狀態。
既然可以傳遞物件,那麼我們也可以在Request 初始化的時候,將所需要的物件注入至Request 裡面,然後再到到Page / Controller 取出來用;在不同的專案範本可以使用的Request 物件都不太一樣,接下來分享我已經知道的寫法。
開發環境
VS IDE 2019
IIS主機ASP.NET 4.8 WebForm / MVC5 / Web API
OWIN主機Web API
ASP.NET Core 3.1
存放狀態的方式是key-value,型別為IDictionary or IDictionary<string,object>
System.Web.HttpContext.Items
.NET 2.0的時代用HttpContext.Items (IDictionary Type),到了.NET 3.5之後可以改用HttpContextBase.Items。
HttpContextWrapper則是用來把HttpContext變成HttpContextBase。
HttpContextBase是一個抽象,可以讓我們更好測試 [Unit Test]使用HttpContextBase取代HttpContext.Current,提高可測試性
HttpContext.Items 是IDictionary型別,Key對應Object。
適用ASP.NET WebForm、ASP.NET MVC。
從Global.asax注入Member物件至 HttpContext.Items
public class Global : HttpApplication{ protected void Application_BeginRequest() { var member = new Member {Id = Guid.NewGuid(), Name = Name.FullName()}; var key = member.GetType().FullName; HttpContext.Current.Items[key] = member; }}
在Default.aspx.cs取出,這裡我用了HttpContextWrapper把HttpContext轉成HttpContextBase
public partial class Default : Page{ protected void Page_Load(object sender, EventArgs e) { if (this.IsPostBack) { return; } var httpContext = new HttpContextWrapper(HttpContext.Current); var key = typeof(Member).FullName; var member = httpContext.Items[key] as Member; this.Id_Label.Text = member.Id.ToString(); this.Name_Label.Text = member.Name; }}
System.Web.HttpContextBase.Items
Controller 依賴HttpContextBase 非HttpContext
適用ASP.NET MVC5
在 ActionFilterAttribute 注入 Member 物件至 HttpContextBase.Items
public class InjectionAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { //初始化物件 var member = new Member {Id = Guid.NewGuid(), Name =Faker.Name.FullName()}; var key = member.GetType().FullName; //注入到 HttpContextBase filterContext.RequestContext.HttpContext.Items[key] = member; } }
在 Controller 取出 Member 物件
public class HomeController : Controller { // GET: Default public ActionResult Index() { var key = typeof(Member).FullName; var member = this.HttpContext.Items[key]; return View(member); } }
System.Net.Http.HttpRequestMessage.Properties
HttpRequestMessage.Properties [“ key”] 是IDictionary <string,object>型別
適用的ASP.NET Web API / ASP.NET Core Web API
在 ActionFilterAttribute 注入 Member 物件至 HttpRequestMessage.Properties["key"]
public class InjectionAttribute : ActionFilterAttribute { public override void OnActionExecuting(HttpActionContext filterContext) { //初始化物件 var member = new Member {Id = Guid.NewGuid(), Name = Faker.Name.FullName()}; var key = member.GetType().FullName; //注入到 HttpRequestMessage filterContext.Request.Properties[key] = member; } }
在 ApiController 取出 Member 物件
public class DefaultController : ApiController { // GET: api/Default public IHttpActionResult Get() { var key = typeof(Member).FullName; var member = this.Request.Properties[key] as Member; return this.Ok(member); } }
Microsoft.Owin.IOwinContext.Environment
IOwinContext.Environment 是IDictionary<string,object>型別
IOwinContext.Set/Get骨子裡面是控制IOwinContext.Environment
適用OWIN
app.Use Middleware 注入 Member 物件至 IOwinContext.Environment["key"]
public class Startup { public void Configuration(IAppBuilder app) { var config = new HttpConfiguration(); // Web API configuration and services // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new {id = RouteParameter.Optional} ); app.Use(async (owinContext, next) => { var member = new Member { Id = Guid.NewGuid(), Name = Name.FullName() }; //owinContext.Set(member.GetType().FullName, member); owinContext.Environment[member.GetType().FullName] = member; await next(); }); app.UseErrorPage() .UseWebApi(config); } }
在 ApiController ,用 IOwinContext.Get 取出 Member 物件
public class DefaultController : ApiController { // GET: api/Default public IHttpActionResult Get() { var key = typeof(Member).FullName; var member = this.Request.GetOwinContext().Get<Member>(key); return this.Ok(member); } }
Microsoft.AspNetCore.Http.HttpContext.Items
HttpContext.Items 是IDictionary<object,object>型別
適用ASP.NET Core
app.Use Middleware 注入 Member 物件至 HttpContext.Items
public class Startup { public IConfiguration Configuration { get; } public Startup(IConfiguration configuration) { this.Configuration = configuration; } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.Use(async (owinContext, next) => { var member = new Member { Id = Guid.NewGuid(), Name = Faker.Name.FullName() }; var key = member.GetType().FullName; owinContext.Items[key] = member; await next(); }); app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); } }
在 Controller 用 HttpContext.Items 取出 Member
[ApiController] [Route("api/[controller]")] public class DefaultController : ControllerBase { [HttpGet] public async Task<ActionResult<Member>> Get() { var key = typeof(Member).FullName; var member = this.HttpContext.Items[key] as Member; return this.Ok(member); } }
來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/69979777/viewspace-2709521/,如需轉載,請註明出處,否則將追究法律責任。
相關文章
- 從request中傳遞過來的引數資訊
- 引數傳遞
- Mybatis引數傳遞MyBatis
- React事件傳遞引數React事件
- 路由元件傳遞引數路由元件
- JS的方法引數傳遞(按值傳遞)JS
- pytest-引數request的使用
- 引數傳遞方式必須是const引用傳遞
- 引數的定義和引數的傳遞
- Shell學習【引數傳遞】
- linux中main引數傳遞LinuxAI
- 利用閉包傳遞引數
- JavaScript函式傳遞引數JavaScript函式
- out,ref,params引數傳遞
- 請求引數的傳遞
- 函式的引數傳遞函式
- t-on-click 傳遞引數
- 【pytest】使用parametrize將引數化變數傳遞到fixture變數
- pytest介面測試之fixture傳引數request
- 函式作為引數傳遞函式
- C++引數的傳遞方式C++
- [Python] 傳遞引數前面的*或**Python
- 引數傳遞機制之JWTJWT
- JAVA基礎之-引數傳遞Java
- 函式引數傳遞及返回函式
- Python怎麼傳遞不定引數Python
- Java方法04:命令列傳遞引數、可變引數Java命令列
- 使用python指令碼傳遞引數:(三種方式可收藏)Python指令碼
- Python的函式引數傳遞:傳值?引用?Python函式
- 面試官問:Go 中的引數傳遞是值傳遞還是引用傳遞?面試Go
- 帶你深入理解傳遞引數
- GridView傳遞兩個引數的方法View
- apicloud拉起小程式並傳遞引數APICloud
- java 傳遞引數的兩種方式Java
- JavaScript 獲取 url 傳遞引數值JavaScript
- python中函式的引數傳遞Python函式
- Day18--命令列傳遞引數命令列
- Mybatis引數傳遞&註解開發MyBatis