1.传值方法
使用Request的方法(1-3):
1)Query:获取链接?后面的值
如:http://localhost:55842/Home/About?name=kxy
public IActionResult About() { ViewData["Message"] = "Your application description page."; //-------------------------Request-------------------------------- string name = Request.Query["name"];//获取连接 ?name=kxy return Content(name); }
结果:页面显示kxy
2)Form:获取表单Post的值
string name = Request.Form["name"];
3)Cookies:本地保存的值
string name1 = Request.Cookies["name"];
使用HttpContext的方法(4):
4)Session:服务器保存的值
using System.Diagnostics;using Microsoft.AspNetCore.Mvc; using CoreMvc.Models; using Microsoft.AspNetCore.Http;namespace CoreMvc.Controllers { public class HomeController : Controller { public IActionResult Index() { return View(); } public IActionResult About() {//-------------------------HttpContext---------------------------- //--------------------------Session------------------------------- //需要HttpContext需要引用using Microsoft.AspNetCore.Http; HttpContext.Session.SetString("name", "kxy"); string name = HttpContext.Session.GetString("name"); HttpContext.Session.Remove("name"); HttpContext.Session.SetInt32("age", 22); int? age = HttpContext.Session.GetInt32("age"); return Content(name); } } }
而且,需要修改Startup.cs
ConfigureServices方法注入(也就是添加) services.AddSession(); Configure方法添加(告诉Asp.net Core使用内存存储Session数据) app.UseSession();
原文地址:https://www.cnblogs.com/wskxy/p/9307977.html
时间: 2024-10-12 22:30:13