我要求获取url:
public Uri GetAbsoluteUri()
{
var request = _httpContextAccessor.HttpContext.Request;
UriBuilder uriBuilder = new UriBuilder();
uriBuilder.Scheme = request.Scheme;
uriBuilder.Host = request.Host.Host;
uriBuilder.Path = request.Path.ToString();
uriBuilder.Query = request.QueryString.ToString();
return uriBuilder.Uri;
}
public string RootPath => Path.Combine(WebRootPath, RootFolderName);
public string GetProductPicturePath()
{
return Path.Combine(GetAbsoluteUri().ToString(), RootFolderName, ProductPictureFolder);
}
public string GetProductMainPicturePath()
{
string path = Path.Combine(GetAbsoluteUri().ToString(), RootFolderName, ProductPictureFolder, ProductMainPictureFolder);
return path;
}
public string GetNewPath()
{
string productMainPicturePath = GetProductMainPicturePath();
return Path.Combine(productMainPicturePath);
}
最后我使用
GetNewPath()
。
,但这会给我地址:
https://localhost/api/Product/GetProductList/Upload/ProductPictureFolder/ProductMainPicture/77777.png
但是我对此网址有2个问题:
1-它不包含网址https://localhost/api
中的端口,但我需要这样返回:http://localhost:4200/api
2-这包括控制器的名称和ActionName,但我需要这样:https://localhost/Upload/ProductPictureFolder/ProductMainPicture/77777.png
但它为我返回了https://localhost/api/Product/GetProductList/Upload/ProductPictureFolder/ProductMainPicture/77777.png
我不需要这个/api/Product/GetProductList
。
Product :
控制器名称
GetProductList :
ActionName
我该如何解决这个问题?
答案 0 :(得分:4)
1-它不包含网址https://localhost/api中的端口,但我需要这样返回
要获取端口,您可以使用以下代码段:
if (request.Host.Port.HasValue)
uriBuilder.Port = request.Host.Port.Value;
2-这包括控制器的名称和ActionName,但是我 需要这样: https://localhost/Upload/ProductPictureFolder/ProductMainPicture/77777.png
我建议您根据需要而不是根据请求来设置UriBuilder路径。像这样:
// Make your Upload file path here
var relativePath = Path.Combine(folderName, filename);
var request = _httpContextAccessor.HttpContext.Request;
var uriBuilder = new UriBuilder
{
Host = request.Host.Host,
Scheme = request.Scheme,
Path = relativePath
};
if (request.Host.Port.HasValue)
uriBuilder.Port = request.Host.Port.Value;
var imageUrl = uriBuilder.ToString();