簡體   English   中英

如何在 ASP.NET 內核中存儲路由?

[英]How to store a route in ASP.NET Core?

我正在嘗試在 ASP.NET Core 中實現通知系統。 我從每個用戶的Notification class 開始:

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

我有一個帶有Create操作的AssessmentsController ,它為特定用戶創建評估。 創建完成后,我想通知為其創建評估的所有用戶。

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。

提前致謝。

可能你可以看看這個用於 url 生成的輔助方法,它接收 controller 和動作名稱並使用它來發送重定向 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發一次就好了

If you need to store it and then fetch from DB, you can probably store some ids of your assessment in Notification model and then dynamically generate url from it and information about the controller when you render, without storing controller name and action there. 您還可以在代碼中手動從中生成一些路線數據。 這樣,如果您將路由更改為 controller,將正確生成鏈接。 如果您的 controller 名稱將更改,您只需更改部分代碼,這比更改鏈接或數據庫中的 controller 名稱更容易

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM