簡體   English   中英

使用Route屬性無法解析URL.Action結果

[英]Url.Action result does not resolve using Route attribute

我正在重建應用程序的前端,由於其復雜性,我必須在現有的舊業務層上工作。 結果,我們有了被稱為“新聞”和“文檔”的東西,但實際上兩者都是存儲它的“文檔”。

我已經制作了一個DocumentsController,它可以處理所有事情,在控制器上拍了[Route("News/{action=index}")][Route("Documents/{action=index}")]作為新聞或文檔發送給控制器。 到現在為止還挺好。 使用具有[Route("Documents/View/{id}"][Route("News/View/{id}"]屬性的單個ActionResult查看特定文檔也可以,但是我遇到了一個問題當我嘗試使用id以外的任何參數作為參數,但僅用於News部分時。

我的ActionResult方法具有以下定義

[Route("Documents/Download/{documentGuid}/{attachmentGuid}")]
[Route("News/Download/{documentGuid}/{attachmentGuid}")]
public ActionResult Download(Guid documentGuid, Guid attachmentGuid)
...

我的視圖具有以下獲取鏈接

<a href="@Url.Action("Download", "Documents", new { documentGuid = Model.Id, attachmentGuid = attachment.AttachmentId })">Download</a>

每當我將“文檔”作為控制器時,這將完美地生成一個類似於site/Documents/Download/guid/guid的鏈接,但是如果我輸入“新聞”,則會生成一個使用類似於site/News/Download?guid&guid查詢字符串的URL site/News/Download?guid&guid參數並解析為404。如果我隨后手動刪除查詢字符串標記並手動設置URL格式,則可以很好地解決。

這里出了什么問題,我缺少一些矛盾之處?

Url.Action的參數是控制器的名稱和操作的名稱,它僅適用於文檔,因為碰巧您的路由與正確的名稱相對應。 如果要使用特定路由,則必須命名路由,然后使用采用路由名稱的方法之一來構造它。

在傳入請求中查找路由時,路由將使用URL確定匹配的路由。 您輸入的URL是唯一的,因此可以正常工作。

但是,當查找要生成的路由時,MVC將使用路由值來確定匹配的路由。 在此過程的這一部分,將完全忽略URL中的文字片段News/Download/ )。

使用屬性路由時,路由值從您修飾的方法的控制器名稱和操作名稱派生。 因此,在兩種情況下,您的路線值為:

| Key             | Value           |
|-----------------|-----------------|
| controller      | Documents       |
| action          | Download        |
| documentGuid    | <some GUID>     |
| attachmentGuid  | <some GUID>     |

換句話說,您的路線值不是唯一的 因此,路由表中的第一個匹配項始終獲勝。

要解決此問題,可以使用命名路由。

[Route("Documents/Download/{documentGuid}/{attachmentGuid}", Name = "Documents")]
[Route("News/Download/{documentGuid}/{attachmentGuid}", Name = "News")]
public ActionResult Download(Guid documentGuid, Guid attachmentGuid)
...

然后,使用@Url.RouteUrl@Html.RouteLink解析URL。

@Html.RouteLink("Download", "News", new { controller = "Documents", action = "Download", documentGuid = Model.Id, attachmentGuid = attachment.AttachmentId })

要么

<a href="@Url.RouteUrl("News", new { controller = "Documents", action = "Download", documentGuid = Model.Id, attachmentGuid = attachment.AttachmentId })">Download</a>

暫無
暫無

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

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