gpt4 book ai didi

angular - 在 ASP.NET Boilerplate .NET Core v3 中设置和获取 session 变量

转载 作者:行者123 更新时间:2023-12-03 14:42:43 24 4
gpt4 key购买 nike

我正在尝试在某个组件中设置变量值(从 angular 选择组件中选择的选项)以在另一个组件中使用它,而 我不想通过 javascript 使用 window.sessionStorage() 我想在 .NET 核心中使用 session 存储,但问题是我可以设置变量值,但是当我想获取它时,它没有返回值。

以下是我的应用程序服务代码

 public class MainProjectAppService : AsyncCrudAppService<MainProject, MainProjectDto,int,PagedAndSortedResultRequestDto,MainProjectDto>
{



private readonly IHttpContextAccessor _httpContextAccessor;


public MainProjectAppService(IRepository<MainProject, int> repository, IHttpContextAccessor httpContextAccessor) : base(repository)
{

_httpContextAccessor = httpContextAccessor;
}

public void setVaraibleValurinSesseion(int ID)
{
_httpContextAccessor.HttpContext.Session.SetInt32("GID", ID);
}

public int getVaraibleValurFromSesseion()
{
return (int)_httpContextAccessor.HttpContext.Session.GetInt32("GID");

}

这是我更新的 Startup.cs 类代码:
using System;
using System.Linq;
using System.Reflection;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Castle.Facilities.Logging;
using Abp.AspNetCore;
using Abp.AspNetCore.Mvc.Antiforgery;
using Abp.Castle.Logging.Log4Net;
using Abp.Extensions;
using TTT.Configuration;
using TTT.Identity;
using Abp.AspNetCore.SignalR.Hubs;
using Abp.Dependency;
using Abp.Json;
using Microsoft.OpenApi.Models;
using Newtonsoft.Json.Serialization;
using Microsoft.AspNetCore.Http;

namespace TTT.Web.Host.Startup
{
public class Startup
{
private const string _defaultCorsPolicyName = "localhost";

private readonly IConfigurationRoot _appConfiguration;

public Startup(IWebHostEnvironment env)
{
_appConfiguration = env.GetAppConfiguration();
}

public IServiceProvider ConfigureServices(IServiceCollection services)
{
services.AddDistributedMemoryCache(); //added this

services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromSeconds(10);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});//added this
//MVC
services.AddControllersWithViews(
options =>
{
options.Filters.Add(new AbpAutoValidateAntiforgeryTokenAttribute());
}
).AddNewtonsoftJson(options =>
{
options.SerializerSettings.ContractResolver = new AbpMvcContractResolver(IocManager.Instance)
{
NamingStrategy = new CamelCaseNamingStrategy()
};
});

services.AddHttpContextAccessor(); // added this but no need as //I think

services.AddMvc().AddSessionStateTempDataProvider();//added this
services.AddSession();// added this

IdentityRegistrar.Register(services);
AuthConfigurer.Configure(services, _appConfiguration);

services.AddSignalR();

// Configure CORS for angular2 UI
services.AddCors(
options => options.AddPolicy(
_defaultCorsPolicyName,
builder => builder
.WithOrigins(
// App:CorsOrigins in appsettings.json can contain more than one address separated by comma.
_appConfiguration["App:CorsOrigins"]
.Split(",", StringSplitOptions.RemoveEmptyEntries)
.Select(o => o.RemovePostFix("/"))
.ToArray()
)
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials()
)
);

// Swagger - Enable this line and the related lines in Configure method to enable swagger UI
services.AddSwaggerGen(options =>
{
options.SwaggerDoc("v1", new OpenApiInfo() { Title = "TTT API", Version = "v1" });
options.DocInclusionPredicate((docName, description) => true);

// Define the BearerAuth scheme that's in use
options.AddSecurityDefinition("bearerAuth", new OpenApiSecurityScheme()
{
Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey
});
});

// Configure Abp and Dependency Injection
return services.AddAbp<TTTWebHostModule>(
// Configure Log4Net logging
options => options.IocManager.IocContainer.AddFacility<LoggingFacility>(
f => f.UseAbpLog4Net().WithConfig("log4net.config")
)
);
}

public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
{

app.UseAbp(options => { options.UseAbpRequestLocalization = false; }); // Initializes ABP framework.

app.UseCors(_defaultCorsPolicyName); // Enable CORS!

app.UseStaticFiles();

app.UseRouting();

app.UseAuthentication();

app.UseAbpRequestLocalization();
//app.UseHttpContextItemsMiddleware();
app.UseSession(); // <================= I've added this without it //will not work
app.UseEndpoints(endpoints =>
{
endpoints.MapHub<AbpCommonHub>("/signalr");
endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
endpoints.MapControllerRoute("defaultWithArea", "{area}/{controller=Home}/{action=Index}/{id?}");
});

// Enable middleware to serve generated Swagger as a JSON endpoint
app.UseSwagger();
// Enable middleware to serve swagger-ui assets (HTML, JS, CSS etc.)
app.UseSwaggerUI(options =>
{
options.SwaggerEndpoint(_appConfiguration["App:ServerRootAddress"].EnsureEndsWith('/') + "swagger/v1/swagger.json", "TTT API V1");
options.IndexStream = () => Assembly.GetExecutingAssembly()
.GetManifestResourceStream("TTT.Web.Host.wwwroot.swagger.ui.index.html");
}); // URL: /swagger
}
}
}


更新 3:

现在,在 Startup.cs 类中添加了一些配置后,它可以通过 Swagger 工作,但我想通过 angular front 它获取值,如下所示返回

System.InvalidOperationException: 'Nullable 对象必须有一个值。'

Angular 设置代码:
   this.http.post('http://localhost:21021/api/services/app/MainProject/setVaraibleValurinSesseion?ID=555',{ID:555}).subscribe(data=>{
alert('saved');
});

Angular 获取代码:
  this.http.get('http://localhost:21021/api/services/app/MainProject/getVaraibleValurFromSesseion').subscribe(data=>{
console.log("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$");
console.log(data);
console.log(("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^"));
});

最佳答案

查看您的代码后,我发现您没有在启动时初始化 session 服务。要初始化 session ,您需要提供分布式缓存服务并设置 session 服务。这里只是您需要在启动时添加的示例配置位 official documentation .

public void ConfigureServices(IServiceCollection services)
{
services.AddDistributedMemoryCache();

services.AddSession(options =>
{
options.IdleTimeout = TimeSpan.FromSeconds(10);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
// other needed initializations
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseSession();
// other configurations
}

如需更详细的 sample ,请查看 Microsoft samples in GitHub .

即使这样,它也可能对您不起作用,因为您使用 SignalR。文档说明如下:

Session isn't supported in SignalR apps because a SignalR Hub may execute independent of an HTTP context. For example, this can occur when a long polling request is held open by a hub beyond the lifetime of the request's HTTP context.

关于angular - 在 ASP.NET Boilerplate .NET Core v3 中设置和获取 session 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60338574/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com