ASP.NET MVC에서 전체 동작 URL 얻기
이 질문에는 이미 답변이 있습니다.
액션의 전체 URL을 가져 오는 기본 제공 방법이 있습니까?
나는 GetFullUrl("Action", "Controller")
그런 것을 반환 할 것 같은 것을 찾고 있다 http://www.fred.com/Controller/Action
.
내가 찾고있는 이유는 URL이 항상 사이트의 현재 위치를 기준으로 생성 될 수 있도록 생성되는 자동 전자 메일의 URL 하드 코딩을 피하기 위해서입니다.
원하는 프로토콜 (예 : http, https)을 인수로 취하는 Url.Action의 과부하가 있습니다.이를 지정하면 정규화 된 URL을 얻게됩니다.
다음은 조치 메소드에서 현재 요청의 프로토콜을 사용하는 예입니다.
var fullUrl = this.Url.Action("Edit", "Posts", new { id = 5 }, this.Request.Url.Scheme);
HtmlHelper (@Html)에는 면도기에서 앵커 요소를 만드는 데 사용할 수있는 ActionLink 메서드의 오버로드가 있지만 hostName 및 fragment 매개 변수도 필요합니다. 따라서 @ Url.Action을 다시 사용하도록 선택했습니다.
<span>
Copy
<a href='@Url.Action("About", "Home", null, Request.Url.Scheme)'>this link</a>
and post it anywhere on the internet!
</span>
Paddy가 언급했듯이 : 과부하를 사용하면 UrlHelper.Action()
명시 적으로 사용할 프로토콜을 지정하면 생성 된 URL은 상대적이 아니라 절대적이고 정규화됩니다.
나는 UrlHelper 클래스 를 사용하여 절대 작업 URL을 작성하는 방법 이라는 블로그 게시물 을 작성했습니다. 여기에서는 가독성을 위해 사용자 정의 확장 메소드를 작성하도록 제안합니다.
/// <summary>
/// Generates a fully qualified URL to an action method by using
/// the specified action name, controller name and route values.
/// </summary>
/// <param name="url">The URL helper.</param>
/// <param name="actionName">The name of the action method.</param>
/// <param name="controllerName">The name of the controller.</param>
/// <param name="routeValues">The route values.</param>
/// <returns>The absolute URL.</returns>
public static string AbsoluteAction(this UrlHelper url,
string actionName, string controllerName, object routeValues = null)
{
string scheme = url.RequestContext.HttpContext.Request.Url.Scheme;
return url.Action(actionName, controllerName, routeValues, scheme);
}
그런 다음 뷰에서 간단히 사용할 수 있습니다.
@Url.AbsoluteAction("Action", "Controller")
이것은 당신이해야 할 일입니다.
@Url.Action(action,controller, null, Request.Url.Scheme)
이것은 단지 정말 까다 롭지 만 상수를 한 번만 정의하고 싶습니다. 위에서 정의한 방법 중 하나를 사용하면 동작 상수가 여러 번 정의됩니다.
이를 피하려면 다음을 수행하십시오.
public class Url
{
public string LocalUrl { get; }
public Url(string localUrl)
{
LocalUrl = localUrl;
}
public override string ToString()
{
return LocalUrl;
}
}
public abstract class Controller
{
public Url RootAction => new Url(GetUrl());
protected abstract string Root { get; }
public Url BuildAction(string actionName)
{
var localUrl = GetUrl() + "/" + actionName;
return new Url(localUrl);
}
private string GetUrl()
{
if (Root == "")
{
return "";
}
return "/" + Root;
}
public override string ToString()
{
return GetUrl();
}
}
그런 다음 컨트롤러를 만듭니다 (예 : DataController).
public static readonly DataController Data = new DataController();
public class DataController : Controller
{
public const string DogAction = "dog";
public const string CatAction = "cat";
public const string TurtleAction = "turtle";
protected override string Root => "data";
public Url Dog => BuildAction(DogAction);
public Url Cat => BuildAction(CatAction);
public Url Turtle => BuildAction(TurtleAction);
}
그런 다음 다음과 같이 사용하십시오.
// GET: Data/Cat
[ActionName(ControllerRoutes.DataController.CatAction)]
public ActionResult Etisys()
{
return View();
}
그리고 .cshtml (또는 모든 코드)에서
<ul>
<li><a href="@ControllerRoutes.Data.Dog">Dog</a></li>
<li><a href="@ControllerRoutes.Data.Cat">Cat</a></li>
</ul>
이것은 확실히 더 많은 작업이지만 컴파일 시간 유효성 검사가 내 편임을 알고 쉽게 쉬고 있습니다.
이 문제가 발생하여 서버가로드 밸런서 뒤에서 실행 중이었습니다. 로드 밸런서가 SSL / TLS 연결을 종료했습니다. 그런 다음 http를 사용하여 요청을 웹 서버에 전달했습니다.
Request.Url.Schema와 함께 Url.Action () 메서드를 사용하여 필자의 경우 자동 전자 메일 (PenTester가 좋아하지 않는)에 링크를 만들기 위해 http URL을 계속 생성했습니다.
약간의 바람을 피 웠지만 https URL을 강제로 작성하는 데 필요한 것입니다.
<a href="@Url.Action("Action", "Controller", new { id = Model.Id }, "https")">Click Here</a>
실제로 web.config AppSetting을 사용하므로 로컬에서 디버깅 할 때 http를 사용할 수 있지만 모든 테스트 및 제품 환경은 변환을 사용하여 https 값을 설정합니다.
이 질문은 ASP .NET에만 해당되지만 일부 상황에서는 시스템에 무관 한 자바 스크립트가 도움이 될 것입니다.
업데이트 : 페이지 외부에서 URL을 형성하는 방법은 위의 답변에 잘 설명되어 있습니다.
또는 다음과 같은 oneliner를 할 수 있습니다.
new UrlHelper(actionExecutingContext.RequestContext).Action(
"SessionTimeout", "Home",
new {area = string.Empty},
actionExecutingContext.Request.Url!= null?
actionExecutingContext.Request.Url.Scheme : "http"
);
필터에서 또는
new UrlHelper(this.Request.RequestContext).Action(
"Details",
"Journey",
new { area = productType },
this.Request.Url!= null? this.Request.Url.Scheme : "http"
);
그러나 꽤 자주 현재 페이지의 URL을 가져와야합니다. 사용중인 페이지의 Html.Action
이름과 컨트롤러를 사용 하고 배치 하는 경우 어색합니다. 그러한 경우에는 JavaScript를 대신 사용하는 것이 좋습니다. 이것은 절반으로 다시 작성된 MVT 절반 웹 양식 인 절반 vb- 스크립트 절반 인 시스템에서 특히 좋습니다. 신은 무엇을 알고 있으며 현재 페이지의 URL을 얻으려면 매번 다른 방법을 사용해야합니다.
한 가지 방법은 자바 스크립트 URL이 들어갈 때 사용하는 window.location.href
또 다른 -document.URL
참고 URL : https://stackoverflow.com/questions/2005367/getting-full-url-of-action-in-asp-net-mvc
'development' 카테고리의 다른 글
ui-router의 ui-sref를 사용하여 매개 변수를 컨트롤러에 전달하는 방법 (0) | 2020.02.28 |
---|---|
Heroku에서 node.js 앱을 만들 때 git에 node_modules를 체크인해야합니까? (0) | 2020.02.28 |
JavaScript 경고 상자의 줄 바꿈 (0) | 2020.02.28 |
파이썬 사전 이해 (0) | 2020.02.28 |
모든 분기에서 문자열을 도입 한 Git 커밋을 찾는 방법은 무엇입니까? (0) | 2020.02.28 |