source

ASP에서 작업의 전체 URL을 가져오는 중입니다.NET MVC

ittop 2023. 5. 7. 11:48
반응형

ASP에서 작업의 전체 URL을 가져오는 중입니다.NET MVC

작업의 전체 URL을 가져오는 기본 제공 방법이 있습니까?

저는 다음과 같은 것을 찾고 있습니다.GetFullUrl("Action", "Controller")그것은 비슷한 것을 돌려줄 것입니다.http://www.fred.com/Controller/Action.

제가 이것을 찾는 이유는 자동으로 생성되는 이메일에서 URL을 하드코딩하지 않기 때문에 사이트의 현재 위치를 기준으로 URL을 항상 생성할 수 있습니다.

Url이 오버로드되었습니다.원하는 프로토콜(예: http, https)을 인수로 사용하는 작업 - 이를 지정하면 정규화된 URL이 표시됩니다.

다음은 작업 방법에서 현재 요청의 프로토콜을 사용하는 예제입니다.

var fullUrl = this.Url.Action("Edit", "Posts", new { id = 5 }, this.Request.Url.Scheme);

HtmlHelper(@Html)에도 앵커 요소를 만들기 위해 레이저에서 사용할 수 있는 ActionLink 메서드가 오버로드되어 있지만 hostName 및 fragment 매개 변수도 필요합니다.그래서 저는 그냥 @Url을 사용하는 것을 선택했습니다.다시 수행:

<span>
  Copy
  <a href='@Url.Action("About", "Home", null, Request.Url.Scheme)'>this link</a> 
  and post it anywhere on the internet!
</span>

Paddy가 언급했듯이, 사용할 프로토콜을 명시적으로 지정하는 오버로드를 사용하면 생성된 URL은 상대적인 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)

이 질문은 ASP에만 해당됩니다.NET 그러나 나는 당신들 중 일부가 많은 상황에서 유익한 시스템에 구애받지 않는 자바스크립트의 혜택을 받을 것이라고 확신합니다.

업데이트: 페이지 외부에서 URL을 생성하는 방법은 위의 답변에서 잘 설명되어 있습니다.

또는 다음과 같이 한 줄기 작업을 수행할 수 있습니다.

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그리고 당신이 있는 페이지의 이름과 컨트롤러를 나에게 입력하는 것은 어색합니다.그런 경우에 제가 선호하는 것은 자바스크립트를 대신 사용하는 것입니다.이것은 특히 반쯤 다시 작성된 MVT 반 웹 형태 반 vb-script 반 신이 알고 있는 시스템에서 좋습니다. 그리고 현재 페이지의 URL을 얻으려면 매번 다른 방법을 사용해야 합니다.

가지 방법은 입니다.window.location.href 다른 - 또다른 -document.URL

서버가 로드 밸런서 뒤에서 실행되고 있어 문제가 발생했습니다.로드 밸런서가 SSL/TLS 연결을 종료하는 중입니다.그런 다음 http를 사용하여 요청을 웹 서버로 전달했습니다.

URL을 사용합니다.요청이 있는 작업() 메서드입니다.Url.Schema, 그것은 계속해서 http url을 만들었고, 나의 경우에는 자동화된 이메일에 링크를 만들었습니다(내 펜테스터는 그것을 좋아하지 않았습니다).

제가 조금 속였을 수도 있지만, 그것이 바로 제가 https URL을 강요하기 위해 필요한 것입니다.

<a href="@Url.Action("Action", "Controller", new { id = Model.Id }, "https")">Click Here</a>

실제로 web.config AppSetting을 사용하여 로컬로 디버깅할 때 http를 사용할 수 있지만 모든 테스트 및 prod 환경에서는 변환을 사용하여 https 값을 설정합니다.

이것은 단지 제가 정말로 까다롭기 때문일 수도 있지만, 저는 상수를 한 번만 정의하는 것을 좋아합니다.위에서 정의한 접근 방식 중 하나를 사용하면 작업 상수가 여러 번 정의됩니다.

이 문제를 방지하려면 다음을 수행할 수 있습니다.

    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();
        }
    }

그런 다음 컨트롤러를 만듭니다. 예를 들어 데이터 컨트롤러:

    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>

이것은 확실히 훨씬 더 많은 작업이지만 컴파일 시간 검증이 내 편이기 때문에 안심입니다.

언급URL : https://stackoverflow.com/questions/2005367/getting-full-url-of-action-in-asp-net-mvc

반응형