【问题标题】:How to store a route in ASP.NET Core?如何在 ASP.NET Core 中存储路由?
【发布时间】:2021-04-18 12:35:25
【问题描述】:

我正在尝试在 ASP.NET Core 中实现通知系统。我从每个用户的 Notification 类开始:

class Notification
{
    public int Id { get; set; }
    public IdentityUser User { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
}

我有一个 AssessmentsController 和一个 Create 操作,可以为特定用户创建评估。创建评估后,我想通知为其创建评估的所有用户。

class AssessmentsController : Controller
{
   public async Task<IActionResult> Create(CreateViewModel model)
   {
         // Create assessment for some users
         _context.Add(assessment);
         
         
         List<Notification> notifications = new();
         foreach(var user in users)
         {
             Notification notif = new() 
             { 
               User = assessment.User, 
               Title = "New Assessment",
               Description = "You have a new assessment scheduled for you" 
             }
             notifications.Add(notif);
         }
         await _context.AddRangeAsync(notifications);
         await _context.SaveChangesAsync(); 
         return RedirectToAction(nameof(Index));
   }
}

当用户点击通知时,我想将用户带到特定页面。如何将通知与该页面的路由相关联?这是通知外观的一个非常淡化的版本:

@model Notification

    <h5> @Model.Title </h5>
    <p>  @Model.Description </p>
    <a @* what to include here? *@> View </a>
}

我能想到的一种方法是将以下属性添加到Notification

public string Area { get; set; }
public string Controller { get; set; }
public string Action { get; set; }
public Dictionary<string, string> Params { get; set; }

然后以下将起作用:

<a 
    asp-area="@notif.Area" 
    asp-controller="@notif.Controller" 
    asp-action="@notif.Action" 
    asp-all-route-data="@notif.Params"> View </a>

但我认为这仅适用于 MVC,并不全面。另外,以后如果页面名称不小心发生了变化,通知也就没用了。

我以前从未使用过通知。有人可以帮我弄这个吗?通知通常是如何实现的?我目前没有使用 SignalR 之类的东西。目前都是服务器端的。我在 PostgreSQL 中使用 Identity and Entity Framework Core 5。

提前致谢。

【问题讨论】:

  • 也许this 可能会有所帮助。如果您的应用程序都是服务器端的,您将如何向用户推送通知?我的意思是,如果您不需要即时通知,则可以在每次页面加载时检查通知。

标签: c# asp.net asp.net-core .net-core push-notification


【解决方案1】:

也许你可以看看这个用于 url 生成的辅助方法,它接收控制器和操作名称并使用它来发送重定向 url

https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.urlhelperextensions.action?view=aspnetcore-5.0#Microsoft_AspNetCore_Mvc_UrlHelperExtensions_Action_Microsoft_AspNetCore_Mvc_IUrlHelper_System_String_System_String_System_Object_

但是长时间存储它并不是一个好主意,因为你的控制器和动作路由可能会改变。 用 SignalR 发送一次就好了

如果您需要存储它然后从数据库中获取,您可能可以在通知模型中存储您评估的一些 id,然后在渲染时从它动态生成 url 和有关控制器的信息,而不在那里存储控制器名称和操作.您还可以在代码中手动从中生成一些路线数据。 这样,如果您更改到控制器的路由,将正确生成链接。如果你的控制器名称会改变,你只需要改变你的代码的一部分,这比在数据库中更改链接或控制器名称更容易

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-04
    • 2021-10-17
    • 2021-06-10
    • 2017-07-10
    • 2020-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多