[ASP.NET]使用Request傳遞參數(shù)-創(chuàng)新互聯(lián)

ASP.NET 的Request 物件的生命周期很短,只會出現(xiàn)在一個Http Request,當(dāng)需要跨物件傳遞資料時,比如HttpModule、HttpHandler、Page 、Controller,可以善用Request 物件來存放短暫的狀態(tài)。

創(chuàng)新互聯(lián)專注為客戶提供全方位的互聯(lián)網(wǎng)綜合服務(wù),包含不限于網(wǎng)站設(shè)計、成都網(wǎng)站建設(shè)、曹妃甸網(wǎng)絡(luò)推廣、重慶小程序開發(fā)公司、曹妃甸網(wǎng)絡(luò)營銷、曹妃甸企業(yè)策劃、曹妃甸品牌公關(guān)、搜索引擎seo、人物專訪、企業(yè)宣傳片、企業(yè)代運(yùn)營等,從售前售中售后,我們都將竭誠為您服務(wù),您的肯定,是我們大的嘉獎;創(chuàng)新互聯(lián)為所有大學(xué)生創(chuàng)業(yè)者提供曹妃甸建站搭建服務(wù),24小時服務(wù)熱線:13518219792,官方網(wǎng)址:muchs.cn

既然可以傳遞物件,那么我們也可以在Request 初始化的時候,將所需要的物件注入至Request 里面,然后再到到Page / Controller 取出來用;在不同的專案范本可以使用的Request 物件都不太一樣,接下來分享我已經(jīng)知道的寫法。

開發(fā)環(huán)境

VS IDE 2019

IIS主機(jī)ASP.NET 4.8 WebForm / MVC5 / Web API

OWIN主機(jī)Web API

ASP.NET Core 3.1

存放狀態(tài)的方式是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對應(yīng)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轉(zhuǎn)成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);
    }
}

文章題目:[ASP.NET]使用Request傳遞參數(shù)-創(chuàng)新互聯(lián)
文章源于:http://muchs.cn/article20/dejgco.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供App開發(fā)、品牌網(wǎng)站制作、服務(wù)器托管、網(wǎng)站收錄、自適應(yīng)網(wǎng)站微信公眾號

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

商城網(wǎng)站建設(shè)