RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / 问题

问题[asp.net-core-mvc]

Martin Hope
Dmitro Nychyporuk
Asked: 2022-07-26 00:11:02 +0000 UTC

使用非直接表C#Asp .net实体执行创建时如何在视图中获取数据

  • 0

您好,我想设置我的应用程序,以便在 PareSubgroup 表中创建新字段时,在我的选择字段中的视图中,创建时,它返回的不是 Schedule 表中的 id,而是主题表中的学科名称。 这就是它的样子

 public IActionResult Create()
    {
        ViewData["Pare_Id"] = new SelectList(_context.Schedules, "Id", "Id");
        ViewData["Subgroup_Id"] = new SelectList(_context.Subgroups, "Id", "Id");
        return View();
    }


    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create([Bind("Pare_Id,Subgroup_Id")] PareSubgroup pareSubgroup)
    {
        if (ModelState.IsValid)
        {
            _context.Add(pareSubgroup);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
        ViewData["Pare_Id"] = new SelectList(_context.Schedules, "Id", "Id", pareSubgroup.Pare_Id);
        ViewData["Subgroup_Id"] = new SelectList(_context.Subgroups, "Id", "Id", pareSubgroup.Subgroup_Id);
        return View(pareSubgroup);
    }

@{ ViewData["Title"] = "Create"; }

<h1>Create</h1>

<h4>PareSubgroup</h4>
<hr />
<div class="row">
  <div class="col-md-4">
    <form asp-action="Create">
      <div asp-validation-summary="ModelOnly" class="text-danger"></div>
      <div class="form-group">
        <label asp-for="Pare_Id" class="control-label"></label>
        <select asp-for="Pare_Id" class="form-control" asp-items="ViewBag.Pare_Id"></select>
      </div>
      <div class="form-group">
        <label asp-for="Subgroup_Id" class="control-label"></label>
        <select asp-for="Subgroup_Id" class="form-control" asp-items="ViewBag.Subgroup_Id"></select>
      </div>
      <div class="form-group">
        <input type="submit" value="Create" class="btn btn-primary" />
      </div>
    </form>
  </div>
</div>

<div>
  <a asp-action="Index">Back to List</a>
</div>

@section Scripts { @{await Html.RenderPartialAsync("_ValidationScriptsPartial");} }

数据模型

c# asp.net-core-mvc
  • 1 个回答
  • 39 Views
Martin Hope
Денис
Asked: 2022-07-13 19:20:52 +0000 UTC

ASP.NET 核心 MVC。实现 IDataProtectionKeyContext 接口

  • 1

有一个数据上下文:

public class OurDbContext : DbContext, IOurDbContext, IDataProtectionKeyContext
{
    public DbSet<Employee> Employees { get; set; }
    
    public DbSet<Role> Roles { get; set; }
    
    public DbSet<DataProtectionKey> DataProtectionKeys { get; set; } = null!;
}

有一种方法可以实现向数据库发送数据:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> CreateNewClient(Employee client, string TypeOfClient)
{
    var secstring = _protector.Protect(client.Password);

    Employee temp = new Employee
    {
        Name = client.Name,
        Password = secstring,
        RoleId = 1
    };
    await _mediatr.Send(new NewEmployee.NewEmployeeCommand(temp));
    return Redirect("~/");
}

没有任何东西进入数据库。

如果我们从上下文类中删除实现IDataProtectionKeyContext

public DbSet<DataProtectionKey> DataProtectionKeys { get; set; } = null!;

并缩短线路

builder.Services.AddDataProtection().PersistKeysToDbContext<OurDbContext>();

前

builder.Services.AddDataProtection();

然后数据以加密密码进入数据库。但在这种情况下,5 分钟后,尝试读取此密码将由于密钥过期而导致异常。

微软的帮助没有说明这一点:

https://docs.microsoft.com/en-us/aspnet/core/security/data-protection/configuration/overview?view=aspnetcore-6.0#persistkeystodbcontext

asp.net-core-mvc entity-framework-core
  • 1 个回答
  • 18 Views
Martin Hope
GoodBoyAlex
Asked: 2022-06-13 03:06:04 +0000 UTC

Hangfire 任务未运行

  • 0

ASP.Net 6.0 上有一个站点。在 Configure startyp.cs 中创建了一个初始化类

public static class SiteInit
{
    private static void AddTasks (IServiceProvider serviceProvider, [NotNull] IConfiguration configuration)
        {
            //Получаю DependencyIjector
            serviceProvider = serviceProvider.CreateScope().ServiceProvider;
            //Провожу инъекцию аккаунта
            AccountManager account = serviceProvider.GetRequiredService<AccountManager>();

            byte.TryParse(configuration["accountsettings:newbieexceededhours"], out byte hourstodelete);

        /* To-Do после теста отключить на Dayly */
        RecurringJob.AddOrUpdate(() => NewbieDeleterTask.Execute(account, hourstodelete), Cron.Hourly);
    }
    public static void InitSite (IServiceProvider service,[NotNull] IConfiguration configuration)
    {
        AddTasks(service, configuration);
    }
}

它的任务是初始化类中给出的任务:

/// <summary>
/// Задача удаления новичков после n часов
/// </summary>
public static class NewbieDeleterTask
{
    private static async Task ExecuteAsync ([NotNull] AccountManager account, byte hours = 36)
    {
        //Получение текущей даты
        DateTime dateTime = DateTime.UtcNow;

        //Получение списока пользователей с неподтверждённым email
        IEnumerable<MyUser> notConfirmedUsers = account.GetAllUsers().Where(usr => !usr.EmailConfirmed);

        //Список "просроченных" пользователей
        // ReSharper disable once CollectionNeverQueried.Local
        List<MyUser> overdueUsers = new();

        //Получаем список просрочек
        foreach (MyUser user in notConfirmedUsers)
        {
            if (await account.IsUserInRoleAsync(user, "newbie") && user.DateOfRegister.AddHours(hours).CompareTo(dateTime) <= 0)
                overdueUsers.Add(user);
        }

        //Удаляем пользователей
        foreach (MyUser user in overdueUsers)
            await account.DeleteUserAsync(user);
    }

    public static void Execute([NotNull] AccountManager account, byte hours = 36) =>
        ExecuteAsync(account, hours).GetAwaiter().GetResult();
}

AccountManager 本身是 usermanager 和 rolemanager 类的包装器。

一般来说,Hangfire 是这样发誓的:

warn: Hangfire.AutomaticRetryAttribute[0]
      Failed to process the job '10004': an exception occurred. Retry attempt 1 of 10 will be performed in 00:00:21.
      System.NullReferenceException: Object reference not set to an instance of an object.
         at rnrmm.Platform.AccountManager.GetAllUsers() in E:\WebSites\rnrmm_ru\rnrmm_ru\Platform\AccountManager.cs:line 69
         at rnrmm.Tasks.NewbieDeleterTask.ExecuteAsync(AccountManager account, Byte hours) in E:\WebSites\rnrmm_ru\rnrmm_ru\Tasks\NewbieDeleterTask.cs:line 25
         at rnrmm.Tasks.NewbieDeleterTask.Execute(AccountManager account, Byte hours) in E:\WebSites\rnrmm_ru\rnrmm_ru\Tasks\NewbieDeleterTask.cs:line 44
warn: Hangfire.AutomaticRetryAttribute[0]
      Failed to process the job '10004': an exception occurred. Retry attempt 2 of 10 will be performed in 00:00:24.
      System.NullReferenceException: Object reference not set to an instance of an object.
         at rnrmm.Platform.AccountManager.GetAllUsers() in E:\WebSites\rnrmm_ru\rnrmm_ru\Platform\AccountManager.cs:line 69
         at rnrmm.Tasks.NewbieDeleterTask.ExecuteAsync(AccountManager account, Byte hours) in E:\WebSites\rnrmm_ru\rnrmm_ru\Tasks\NewbieDeleterTask.cs:line 25
         at rnrmm.Tasks.NewbieDeleterTask.Execute(AccountManager account, Byte hours) in E:\WebSites\rnrmm_ru\rnrmm_ru\Tasks\NewbieDeleterTask.cs:line 44

GetAllUsers函数本身如下所示:

public List<MyUser> GetAllUsers ()
    {
        IQueryable<MyUser> usersQuery = usermanager.Users;
        return usersQuery.ToList();
    }

怎么了?为什么她没有获得用户(网站上有 3 个用户)!

asp.net-core-mvc
  • 1 个回答
  • 10 Views
Martin Hope
zodiak1
Asked: 2020-12-02 18:24:25 +0000 UTC

应该在哪里使用数据库?

  • 1

在哪里被认为是正确的使用数据库?在控制器中还是在单独的文件中?

asp.net-core-mvc
  • 1 个回答
  • 10 Views
Martin Hope
Виталий Шебаниц
Asked: 2020-12-24 02:44:43 +0000 UTC

用户授权检查

  • -1

if (!Yii::$app->user->isGuest)您只需要( Yii2)之类的东西asp.net core。我需要知道用户是否登录。

试过System.Security.Claims.User.Identity.IsAuthenticated了,但它一直在false ,所以错误是:HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;

asp.net-core-mvc
  • 1 个回答
  • 10 Views

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    我看不懂措辞

    • 1 个回答
  • Marko Smith

    请求的模块“del”不提供名为“default”的导出

    • 3 个回答
  • Marko Smith

    "!+tab" 在 HTML 的 vs 代码中不起作用

    • 5 个回答
  • Marko Smith

    我正在尝试解决“猜词”的问题。Python

    • 2 个回答
  • Marko Smith

    可以使用哪些命令将当前指针移动到指定的提交而不更改工作目录中的文件?

    • 1 个回答
  • Marko Smith

    Python解析野莓

    • 1 个回答
  • Marko Smith

    问题:“警告:检查最新版本的 pip 时出错。”

    • 2 个回答
  • Marko Smith

    帮助编写一个用值填充变量的循环。解决这个问题

    • 2 个回答
  • Marko Smith

    尽管依赖数组为空,但在渲染上调用了 2 次 useEffect

    • 2 个回答
  • Marko Smith

    数据不通过 Telegram.WebApp.sendData 发送

    • 1 个回答
  • Martin Hope
    Alexandr_TT 2020年新年大赛! 2020-12-20 18:20:21 +0000 UTC
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5