Programing

Web API 컨트롤러에서 기본 URL을 얻는 방법은 무엇입니까?

crosscheck 2020. 11. 13. 07:50
반응형

Web API 컨트롤러에서 기본 URL을 얻는 방법은 무엇입니까?


Url.Link()특정 경로의 URL을 얻는 데 사용할 수 있다는 것을 알고 있지만 Web API 컨트롤러에서 Web API 기본 URL을 얻으려면 어떻게해야합니까?


( )의 VirtualPathRoot속성을 사용할 수 있습니다.HttpRequestContextrequest.GetRequestContext().VirtualPathRoot


url " http : // localhost : 85458 / api / ctrl / " 에 대한 요청의 조치 메소드에서

var baseUrl = Request.RequestUri.GetLeftPart(UriPartial.Authority) ;

이것은 당신을 얻을 것입니다 http : // localhost : 85458


Url.Content("~/")

나를 위해 일했습니다!


이것이 내가 사용하는 것입니다.

Uri baseUri = new Uri(Request.RequestUri.AbsoluteUri.Replace(Request.RequestUri.PathAndQuery, String.Empty));

그런 다음 다른 상대 경로 와 결합 할 때 다음을 사용합니다.

string resourceRelative = "~/images/myImage.jpg";
Uri resourceFullPath = new Uri(baseUri, VirtualPathUtility.ToAbsolute(resourceRelative));

이 서비스를 컨트롤러에 삽입합니다.

 public class LinkFactory : ILinkFactory
 {
    private readonly HttpRequestMessage _requestMessage;
    private readonly string _virtualPathRoot;


    public LinkFactory(HttpRequestMessage requestMessage)
    {
        _requestMessage = requestMessage;
        var configuration = _requestMessage.Properties[HttpPropertyKeys.HttpConfigurationKey] as HttpConfiguration;
        _virtualPathRoot = configuration.VirtualPathRoot;
        if (!_virtualPathRoot.EndsWith("/"))
        {
            _virtualPathRoot += "/";
        }
    }

    public Uri ResolveApplicationUri(Uri relativeUri)
    {

        return new Uri(new Uri(new Uri(_requestMessage.RequestUri.GetLeftPart(UriPartial.Authority)), _virtualPathRoot), relativeUri);
    }

}

Url 도우미 클래스에서 다음 스 니펫을 사용하세요.

Url.Link("DefaultApi", new { controller = "Person", id = person.Id })

전체 기사는 http://blogs.msdn.com/b/roncain/archive/2012/07/17/using-the-asp-net-web-api-urlhelper.aspx에서 볼 수 있습니다.

This is the official way which does not require any helper or workaround. If you look at this approach is like ASP.NET MVC


new Uri(Request.RequestUri, RequestContext.VirtualPathRoot)

First you get full URL using HttpContext.Current.Request.Url.ToString(); then replace your method url using Replace("user/login", "").

Full code will be

string host = HttpContext.Current.Request.Url.ToString().Replace("user/login", "")

Not sure if this is a Web API 2 addition, but RequestContext has a Url property which is a UrlHelper: HttpRequestContext Properties. It has Link and Content methods. Details here


Base on Athadu's answer, I write an extenesion method, then in the Controller Class you can get root url by this.RootUrl();

public static class ControllerHelper
{
    public static string RootUrl(this ApiController controller)
    {
        return controller.Url.Content("~/");
    }
}

send a GET to a page and the content replied will be the answer.Base url : http://website/api/


In ASP.NET Core ApiController the Request property is only the message. But there is still Context.Request where you can get expected info. Personally I use this extension method:

public static string GetBaseUrl(this HttpRequest request)
{
    // SSL offloading
    var scheme = request.Host.Host.Contains("localhost") ? request.Scheme : "https";
    return $"{scheme}://{request.Host}{request.PathBase}";
}

  1. Add a reference to System.Web using System.Web;

  2. Get the host or any other component of the url you want string host = HttpContext.Current.Request.Url.Host;


Al WebApi 2, just calling HttpContext.Current.Request.Path;


From HttpRequestMessage

request.Headers.Host

참고URL : https://stackoverflow.com/questions/19866192/how-to-get-base-url-in-web-api-controller

반응형