在 ServiceStack 服务中,我希望能够获取请求 HTTP 方案(HTTP 或 HTTPS)、主机名和端口,然后使用它们来构造作为数组(或列表)返回的图像的绝对路径) 的 URL。
服务在 ASP.NET MVC 应用程序中运行(/api 上的并行场景),但这将来可能会更改为自托管 SS,因此如果存在涵盖这两种场景的解决方案,那就太好了让我们以这种方式实现它。
最佳答案
在每个请求或响应过滤器中或在任何 ServiceStack 服务中,您始终可以访问底层 HTTP Request和 Response 。例如如何在您的服务中访问它们:
public class MyService : Service
{
public object Get(Request request)
{
var scheme = base.Request.IsSecureConnection ? "https" : "http";
base.Response...
}
}
如果您需要访问底层 HTTP 请求或响应,您始终可以通过以下方式访问它们:
var aspnetRequest = (HttpRequest) base.Request.OriginalRequest;
var aspnetResponse = (HttpResponse) base.Request.OriginalResponse;
以编程方式构建服务 URL
ServiceStack 允许您使用与以下相同的内置 ToUrl(method,format)
和 ToAbsoluteUrl(method,format)
扩展方法来构造服务的相对或绝对 URL C# 服务客户端使用:
[Route("/customers")]
[Route("/customers/{Id}")]
public class Customers : IReturn<List<Customer>>
{
public int? Id { get; set; }
}
鉴于上述请求 DTO 和定义的路由,您可以构造以下 url,它将使用最相关的 url 来创建 url,例如:
var relativeUrl = new Customers().ToUrl(); // /customers
var absoluteUrl = new Customers().ToAbsoluteUri(); // http://host/api/customers
// /customers/1
var relativeIdUrl = new Customers { Id = 1 }.ToUrl();
// http://host/api/customers/1
var absoluteIdUrl = new Customers { Id = 1 }.ToAbsoluteUri();
关于asp.net-mvc - 在 ServiceStack 服务中获取请求 URL、方案、主机名和端口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15598069/