У меня есть базовое веб-приложение c. net core 3.1. У меня есть класс, чтобы получить информацию о пользователе от сеанса. Проблема в том, что когда я использую эти методы в режиме разработки, все в порядке и работают довольно хорошо, но в производстве, когда я публикую sh и запускаю проект dll с помощью do tnet project_name.dll на локальном хосте, этот метод записи в excel не работает из-за того, что не находит пользователя в сеансе.
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews().AddNewtonsoftJson();
services.AddRazorPages().AddRazorRuntimeCompilation().AddNewtonsoftJson();
services.Configure<CookiePolicyOptions>(options => {
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddSession(options=> {
options.IdleTimeout = TimeSpan.FromMinutes(180);
options.Cookie.HttpOnly = true;
options.Cookie.IsEssential = true;
});
services.AddHttpContextAccessor();
services.AddSingleton<RequestHandler>();
}
// 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();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseSession();
ApplicationContext.Configure(app.ApplicationServices
.GetRequiredService<IHttpContextAccessor>());
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Login}/{action=Index}/{id?}");
});
}
}
program.cs
public class RequestHandler
{
private readonly IHttpContextAccessor _HttpContextAccessor;
public RequestHandler(IHttpContextAccessor httpContextAccessor)
{
this._HttpContextAccessor = httpContextAccessor;
}
public void SetSession(string key,string value)
{
try
{
_HttpContextAccessor.HttpContext.Session.SetString(key, value);
}
catch (Exception)
{
throw;
}
}
public string GetSession(string key)
{
try
{
return _HttpContextAccessor.HttpContext.Session.GetString(key);
}
catch (Exception)
{
throw;
}
}
public void SetUser(PersonelGuvenlik user)
{
try
{
_HttpContextAccessor.HttpContext.Session.SetString("user",JsonConvert.SerializeObject(user));
}
catch (Exception)
{
throw;
}
}
public PersonelGuvenlik GetUser()
{
try
{
var user = GetSession("user");
return JsonConvert.DeserializeObject<PersonelGuvenlik>(user);
}
catch (Exception)
{
return null;
}
}
public void LoginControl()
{
try
{
if (GetUser() == null)
{
_HttpContextAccessor.HttpContext.Response.Redirect("/Login/Index");
}
}
catch (Exception)
{
throw;
}
}
public void RemoveUserSession()
{
try
{
_HttpContextAccessor.HttpContext.Session.Remove("user");
_HttpContextAccessor.HttpContext.Response.Redirect("Login/Index");
}
catch (Exception)
{
throw;
}
}
}
requesthandler.cs
public static class ApplicationContext
{
private static IHttpContextAccessor _httpContextAccessor;
public static void Configure(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public static HttpContext Current => _httpContextAccessor.HttpContext;
}
public static class HttpSessionHelper
{
public static void Set<T>(this ISession session, string key, T value)
{
session.SetString(key, JsonConvert.SerializeObject(value));
}
public static T Get<T>(this ISession session, string key)
{
var value = session.GetString(key);
return value == null ? default(T) :
JsonConvert.DeserializeObject<T>(value);
}
}
и мне нужно написать в Excel метод
[HttpPost]
public async Task<IActionResult> WriteToExcel()
{
using (UnitOfWork unitOfWork = new UnitOfWork(new Context()))
{
string sWebRootFolder = _IWebHostEnvironment.WebRootPath;
string sFileName = string.Concat(Guid.NewGuid(), ".xlsx");
string URL = string.Format("{0}://{1}/{2}", Request.Scheme, Request.Host, sFileName);
FileInfo file = new FileInfo(Path.Combine(sWebRootFolder, sFileName));
var memory = new MemoryStream();
try
{
var personel = await unitOfWork.PgPersonel.GetPersonel(_RequestHandler.GetUser());
DataTable table = (DataTable)JsonConvert.DeserializeObject(JsonConvert.SerializeObject(result), (typeof(DataTable)));
using (var fs = new FileStream(Path.Combine(sWebRootFolder, sFileName), FileMode.Create, FileAccess.Write))
{
IWorkbook workbook = new XSSFWorkbook();
//things to write excel
workbook.Write(fs);
}
using (var stream = new FileStream(Path.Combine(sWebRootFolder, sFileName), FileMode.Open))
{
await stream.CopyToAsync(memory);
}
memory.Position = 0;
return File(memory, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", sFileName);
}
catch (Exception ex)
{
return Json(ex);
}
finally
{
file.Delete();
}
}
}