C#CORE3.1的WEBAPI中SESSION使用
(2022-05-05 19:22:02)
标签:
csessioncore3.1webapi |
分类: 软件开发 |
服务器端
public void
ConfigureServices(IServiceCollection services)
{
services.AddControllers();
//
指定Session保存方式:分发内存缓存
services.Configure(options =>
{
// This lambda determines
whether user consent for non-essential cookies is needed for a
given request.
options.CheckConsentNeeded =
context => false;//这里要改为false,默认是true,true的时候session无效
options.MinimumSameSitePolicy
= SameSiteMode.None;
});
services.AddDistributedMemoryCache();
services.AddSession(option =>
{
option.IOTimeout =
TimeSpan.FromHours(1);
option.IdleTimeout =
TimeSpan.FromHours(1);
option.Cookie.HttpOnly =
true;
// Make the session cookie
essential
option.Cookie.IsEssential =
true;
option.Cookie.Name =
"XMECG";
//默认cookie如果没有信息,会被清空,导致sessionid改变,所以先给个名字
});
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
// SESSION
结束
}
public void Configure(IApplicationBuilder
app, IWebHostEnvironment env)
{
............
app.UseAuthorization();
//启动SESSION
app.UseSession();
app.UseCookiePolicy();
//支持获取IP地址
app.UseForwardedHeaders(new ForwardedHeadersOptions {
ForwardedHeaders = ForwardedHeaders.XForwardedFor |
ForwardedHeaders.XForwardedProto });
//End Sesson
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
//设置
HttpContext.Session.SetString("USERID",
"888");
if
(HttpContext.Session.TryGetValue("USERID", out byte[] bytes))
{
theUserId =
Encoding.UTF8.GetString(bytes);
}
private static CookieContainer
cookie = new CookieContainer();
string url =
"http://xxx/API/HelloWorld";
string theText = "TEST";
byte[] bs =
Encoding.UTF8.GetBytes(theText);
HttpWebRequest theRequest =
(HttpWebRequest)HttpWebRequest.Create(url);
theRequest.Method = "POST";
theRequest.ContentType = "application/json;charset=utf-8";
theRequest.ContentLength = bs.Length;
theRequest.Headers.Set("Cookie", "cookie");
theRequest.CookieContainer = cookie;
using
(Stream reqStream = theRequest.GetRequestStream())
{
reqStream.Write(bs, 0,
bs.Length);
reqStream.Close();
}
using
(Stream reqStream = theRequest.GetRequestStream())
{
reqStream.Write(bs, 0,
bs.Length);
reqStream.Close();
}
using
(WebResponse wr = theRequest.GetResponse())
{
Stream theResponseStream =
wr.GetResponseStream();
StreamReader theReader = new
StreamReader(theResponseStream);
string theOutPut =
theReader.ReadToEnd();
System.Text.UTF8Encoding
converter = new System.Text.UTF8Encoding();
string theBase642 =
converter.GetString(Convert.FromBase64String(theOutPut));
}
1.NUGET 加载PACKAGE
使用NUGET的URL
https://nuget.cdn.azure.cn/v3/index.json
PACKAGE名:
Microsoft.AspNetCore.Session
Microsoft.AspNetCore.HttpOverrides
2. 添加Session配置服务(Startup.cs)
3. 在Controller中使用Session
、//获取
客户端
1.定义CookieContainer
2.POST代码
在HTTP POST时要包括CookieContainer,否则会认为一个新的SESSION
public int APITest()
{
前一篇:咖啡和茶