mare
mare

Reputation: 13083

Getting Request URL, Scheme, Hostname and Port in ServiceStack service

Within ServiceStack service I'd like to be able to get the request HTTP Scheme (HTTP or HTTPS), hostname and port which I would then use to construct the absolute path for images that are being returned as an array (or list) of URLs.

Service runs within the ASP.NET MVC application (the side-by-side scenario at /api) but this could change in the future to self-hosted SS so if a solution that covers both scenarios exists it would be nice to have us implement it that way.

Upvotes: 2

Views: 4102

Answers (1)

mythz
mythz

Reputation: 143319

In every request or response filter or inside any ServiceStack Service you always have access to the underlying HTTP Request and Response. e.g. how to access them in your Service:

public class MyService : Service
{ 
    public object Get(Request request) 
    {
        var scheme = base.Request.IsSecureConnection ? "https" : "http";
        base.Response...
    }
}

If you ever need access to the underlying HTTP Request or Response you can always access them with:

var aspnetRequest = (HttpRequest) base.Request.OriginalRequest;
var aspnetResponse = (HttpResponse) base.Request.OriginalResponse;

Programmatically constructing URLs to Services

ServiceStack lets you construct relative or absolute urls for services by using the same in-built ToUrl(method,format) and ToAbsoluteUrl(method,format) extension methods that the C# Service Clients use:

[Route("/customers")]
[Route("/customers/{Id}")]
public class Customers : IReturn<List<Customer>>
{
    public int? Id { get; set; }
}

Given the above Request DTO and defined routes, you can construct the following urls which will use the most relevant url to create the url, e.g:

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

Upvotes: 4

Related Questions