[英]Generate a url link in .net core api with route values
[route("{value}/download")]
Public IactionResult Download([fromroute] string value)
{
}
我想為上述端點生成一個鏈接,我嘗試使用下面的 actionlink 來生成 URL,但它返回一個空值。
輸出應該是 https://{hostname}/{controlername}/{routevalue}/actionname
Url.ActionLink($"DownLoad", "controller", new { Value= value}, protocol: "https")
Url.ActionLink($"{value}/DownLoad", "controller", new { Value= value}, protocol: "https")
我曾嘗試使用下面的 actionlink 來生成 URL,但它返回一個空值
那是因為 UrlHelper 在控制器中找不到這樣的操作名稱({value}/DownLoad)。
您需要檢查Url.ActionLink
源代碼以了解每個參數代表什么:
//
// Summary:
// Generates an absolute URL for an action method, which contains the specified
// action name, controller name, route values, protocol to use, host name, and fragment.
// Generates an absolute URL if the protocol and host are non-null. See the remarks
// section for important security information.
//
// Parameters:
// helper:
// The Microsoft.AspNetCore.Mvc.IUrlHelper.
//
// action:
// The name of the action method. When null, defaults to the current executing action.
//
// controller:
// The name of the controller. When null, defaults to the current executing controller.
//
// values:
// An object that contains route values.
//
// protocol:
// The protocol for the URL, such as "http" or "https".
//
// host:
// The host name for the URL.
//
// fragment:
// The fragment for the URL.
//
// Returns:
// The generated URL.
//
// Remarks:
// The value of host should be a trusted value. Relying on the value of the current
// request can allow untrusted input to influence the resulting URI unless the Host
// header has been validated. See the deployment documentation for instructions
// on how to properly validate the Host header in your deployment environment.
public static string ActionLink(this IUrlHelper helper, string action = null, string controller = null, object values = null, string protocol = null, string host = null, string fragment = null);
然后您需要更改如下代碼:
@Url.ActionLink($"Download", "ControllerName", new { Value= value}, protocol: "https")
后台代碼:
[Route("[controller]")]
public class HomeController : Controller //controller name here is Home
{
[Route("{value}/download")]
public IActionResult Download([FromRoute] string value)
{
return Ok();
}
}
此代碼已在 Visual Studio 中進行了測試
如果您需要鏈接,對於復雜的路線,您必須使用路線名稱
[Route("[controller]/{value}/download", Name ="download")]
public IActionResult Download(string value)
並查看
@Html.RouteLink( "Go to download", "download", "https",null,null, new { Value=value},null)
它會生成網址
http://xxxx/controller/value/download
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.