ASP.NET MVC 작업에서 절대 URL 가져 오기
이것은 아마도 더미 질문이지만 명확한 표시를 찾을 수 없습니다. 서버에있는 일부 파일의 백업을 관리하는 유일한 목적을 가진 MVC3 웹 응용 프로그램에 POCO 클래스가 있습니다. 일반적으로 백업을 생성하고 컨트롤러에 파일 이름을 반환하면 다운로드 URL이 포함 된 이메일이 전송됩니다. 이것은 잘 작동하지만 보낼 절대 URL을 만들 수 없습니다. 어떤 기능을 사용하든 항상 http://www.somesite.com/Backup/TheFile.zip이 아닌 /Backup/TheFile.zip 과 같은 상대 URL을 얻습니다 . 나는 시도했다 :
VirtualPathUtility.ToAbsolute("~/Backup/SomeFile.zip");
HttpRuntime.AppDomainAppVirtualPath + "/Backup/SomeFile.zip";
Url.Content("~/Backup/SomeFile.zip");
그러나 그들은 모두 /Backup/SomeFile.zip 과 같은 것을 반환합니다 . 어떤 생각?
다음과 같이 할 수 있습니다.
var urlBuilder =
new System.UriBuilder(Request.Url.AbsoluteUri)
{
Path = Url.Action("Action", "Controller"),
Query = null,
};
Uri uri = urlBuilder.Uri;
string url = urlBuilder.ToString();
// or urlBuilder.Uri.ToString()
Url.Action()이 샘플 대신 Url.Content(), 또는 라우팅 방법을 사용하거나 실제로 경로를 전달할 수도 있습니다.
그러나 URL이으로 이동 Controller Action하면 더 간단한 방법이 있습니다.
var contactUsUriString =
Url.Action("Contact-Us", "About",
routeValues: null /* specify if needed */,
protocol: Request.Url.Scheme /* This is the trick */);
여기서 트릭은 protocol라우팅 메서드를 호출 할 때 / scheme 을 지정 하면 절대 URL을 얻는 것입니다. 가능한 경우 이것을 권장 하지만 필요한 경우 첫 번째 예제에서 더 일반적인 방법도 있습니다.
자세한 내용은 http://gurustop.net/blog/2012/03/23/writing-absolute-urls-to-other-actions-in-asp-net-mvc/ 에 블로그를 게시했습니다.
컨트롤러 내에서 :
var path = VirtualPathUtility.ToAbsolute(pathFromPoco);
var url = new Uri(Request.Url, path).AbsoluteUri
이것은 나를 위해 작동합니다.
using System;
using System.Web;
using System.Web.Mvc;
public static class UrlExtensions
{
public static string Content(this UrlHelper urlHelper, string contentPath, bool toAbsolute = false)
{
var path = urlHelper.Content(contentPath);
var url = new Uri(HttpContext.Current.Request.Url, path);
return toAbsolute ? url.AbsoluteUri : path;
}
}
cshtml에서의 사용법 :
@Url.Content("~/Scripts/flot/jquery.flot.menuBar.js", true)
MVC 4의 기본 제공 도우미는 host또는 protocol매개 변수가 비어 있지 않은 경우 절대 URL을 만듭니다 . 뷰에서 사용하는 예제 확장 방법과 함께 여기 에 대한 답변을 참조하십시오 .
ASP.Net Core 2.0 (MVC)에서 이것은 작업에 대한 절대 URL을 생성하는 데 사용됩니다.
var url = Url.Action("About", "Home", new { /*Route values here*/ }, Request.Scheme);
MVC 5를위한 헬퍼 클래스를 작성했습니다. 매우 유연하며 컨트롤러 내부에 있지 않을 때이 기능이 필요한 경우 특히 유용합니다. 프로젝트에 바로 넣을 수 있어야합니다.
Meligy가 지적했듯이 핵심은 프로토콜을 포함하는 것입니다. 여기에 http로 하드 코딩되어 있으므로 SSL을 사용하려면 좀 더 유연해야 할 수도 있습니다.
public class AbsoluteUrlHelper
{
/// <summary>
/// Creates an absolute "fully qualified" url from an action, and assumes the current controller.
/// </summary>
/// <returns></returns>
public static string GetAbsoluteUrl(string action, object routeValues = null)
{
var urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);
var values = urlHelper.RequestContext.RouteData.Values;
var controller = values["controller"].ToString();
return GetAbsoluteUrl(action, controller, urlHelper, routeValues);
}
/// <summary>
/// Creates an absolute "fully qualified" url from an action and controller.
/// </summary>
public static string GetAbsoluteUrl(string action, string controller, object routeValues = null)
{
var urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);
return GetAbsoluteUrl(action, controller, urlHelper, routeValues);
}
/// <summary>
/// Creates an absolute "fully qualified" url from an action and controller.
/// </summary>
public static string GetAbsoluteUrl(string action, string controller, UrlHelper urlHelper, object routeValues = null)
{
var uri = urlHelper.Action(action, controller, routeValues, "http");
return uri;
}
}
몇 가지 옵션이 있습니다.
- HttpContext.Request.Url의 값을 정적 또는 멤버 변수에 저장하고이를 사용하여 정규화 된 경로를 전달합니다.
- Save the app domain in an app setting in the web.config.
- Hard-code the value.
참고URL : https://stackoverflow.com/questions/7406258/getting-absolute-url-fron-an-asp-net-mvc-action
'IT TIP' 카테고리의 다른 글
| 배열 반복 중에 현재 요소가 마지막 요소인지 확인 (0) | 2020.11.03 |
|---|---|
| 쉘 스크립트에서 파이썬 버전 감지 (0) | 2020.11.03 |
| stdint.h와 inttypes.h의 차이점 (0) | 2020.11.03 |
| request.POST.get ( 'sth') 대 request.POST [ 'sth']-차이점? (0) | 2020.11.03 |
| jQuery는 클래스 속성이없는 모든 div를 가져옵니다. (0) | 2020.11.03 |