asp.net core 請求參數接收總結


String key1=Request.Query["key1"];//獲取url字符串
String key2 = Request.Form["key2"];//獲取表單
String key3 = Request.Cookies["key3"];//獲取cookie
String key4 = Request.Headers["key4"];//獲取http頭參數

 注:在.net core 2.1中使用cookie需要設置options.CheckConsentNeeded = context => false;即:

 services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => false; //設置false可以打開cookie
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

在.net core中使用session,需要在Startup.cs文件進行中間件配置等操作,紅色為需要添加的內容:

 public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => false;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            services.AddDbContext<MyContext>(options =>
            {
                options.EnableSensitiveDataLogging(true);//敏感數據記錄,可以控制台生成的sql實際傳的參數顯示出來
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"), opts =>
                {
                    //默認情況下SqlServer限制在1000條,假設1500條批量操作會按2個批次來插入數據庫,第一批次1000條,第二批次500條來進行處理
                    //opts.MaxBatchSize(100000);//設置批量操作一批次大小,比如AddRange批量添加一批次插入數據大小限制
                    //opts.CommandTimeout(72000);//設置超時20分鍾
                });
            });

            services.AddSession(); 


        }
 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();
            app.UseCookiePolicy();
            app.UseSession();
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }

 

//設置session 
HttpContext.Session.SetString("sessionid", "123456789");
//設置cookie
Response.Cookies.Append("key3", "heheda");
//獲取session
String sessionid = HttpContext.Session.GetString("sessionid");
//HttpContext.Session.Remove("sessionid");//刪除session
//獲取cookie
String key3 = Request.Cookies["key3"];

 數據綁定:

 /// <summary>
        /// 數據綁定
        /// </summary>
        public IActionResult SayHello1(String name,int age,string val)
        {
            //get請求: http://localhost:5000/Home/SayHello1?name=zhangsan&age=11&val=abc
            //post請求:使用PostMan測試,Content-Type:application/x-www-form-urlencoded 表單請求可以獲取
            return Content("hello:"+name+",age:"+age+",val:"+val);
        }

模型綁定:查詢字符串或表單key的名稱和類屬性的名稱保持一致就能映射上

 //模型綁定:查詢字符串或表單key的名稱和類屬性的名稱保持一致就能映射上
        public IActionResult SayHello2(TestModel model)
        {
            //get請求: http://localhost:5000/Home/SayHello1?name=zhangsan&age=11
            //post請求:使用PostMan測試,Content-Type:application/x-www-form-urlencoded 表單請求可以獲取
            return Content("hello:" + model.Name + ",age:" + model.Age );
        }

        public class TestModel
        {
            public String Name { get; set; }
            public  int Age { get; set; }
        }

  

 

//限制了只允許通過url字符串和http正文模型綁定參數 
public IActionResult SayHello2([FromQuery][FromBody]TestModel model)
        {
            return Content("hello:" + model.Name + ",age:" + model.Age );
        }

  不是所有的數據都能自動綁定到方法參數上,比如Header就需要制定FromHeaderAttribute.這里測試Header提交的參數並不能進行模型綁定:

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>PostHeader</title>
    
</head>
<body>
<button onclick="postHeader()" >提交帶Header數據</button>
</body>
</html>
<script src="~/lib/jquery/dist/jquery.js"></script>
<script>
    function postHeader() {
        $.ajax({
            url: "/Home/PostHeader?r=" + Math.random(),
            beforeSend: function(xhr) {
                xhr.setRequestHeader("Name", 'zhangsan');
                xhr.setRequestHeader("token", 'djshfdwehh234h3hdjhwhdu23'); 
            },
            data: {Name:'呵呵噠',age:12},
            type: 'post',
            success: function(data) {
                alert(data);
            }
    });
    }
</script>

  后台接收:

   /// <summary>
        /// 不是所有的數據都能自動綁定到方法參數上,比如Header就需要制定FromHeaderAttribute.這里測試Header提交的參數並不能進行模型綁定
        /// </summary>
        [HttpPost]
        public IActionResult PostHeader([FromHeader]String name,[FromHeader]String token,[FromForm]TestModel model)
        {
            return Content("hello " + name + ",Name2:"+model.Name+",age2:"+model.Age);
        }

  

 //返回Json
        public IActionResult ReturnJson()
        {
            //JsonResult result = new JsonResult(new { username = "張三" });
            //return result;

            return Json(new { username = "張三" });
        }

  

  /// <summary>
        /// 返回指定視圖
        /// </summary>
        public IActionResult ShowView()
        {
            return View("~/Views/Home/MyTest.cshtml");
        }

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM