Is there a best practice for supporting self- and web-hosting (at the same time)?
There are many problems I had to solve. Under self-hosting autofac does not work properly, because HttpContext.Current is not set and The GlobalConfiguration is not accessible in self-hosting.
Are there other problems to be aware of?
Have a look at this answer: https://stackoverflow.com/a/13285693/463785 This shows you how you can structure your solution in a hosting layer agnostic way.
Basically, put your ASP.NET Web API logic into a separate project and, as @DarrelMiller suggested, don't use any hosting specific context in that project. Don't even reference unnecessary assemblies (e.g: System.Web) inside this project. However, you will have some hosting layer specific needs, such as getting the consumer's IP address (this cannot be done through what ASP.NET Web API gives you). In such cases, employ some sort of contract between your core API and hosting layers.
For example, below one is the message handler which will set the IP Address of the consumer for each request and I registered this message handler through my WebHost project:
public class UserHostAddressSetterHandler : DelegatingHandler {
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) {
request.Properties[ApiCommonRequestKeys.UserHostAddressKey] = request.GetUserHostAddress();
return base.SendAsync(request, cancellationToken);
}
}
internal static class HttpRequestMessageExtensions {
internal static HttpContextBase GetHttpContext(this HttpRequestMessage request) {
return (HttpContextBase)request.Properties[Constants.MS_HttpContextKey];
}
internal static string GetUserHostAddress(this HttpRequestMessage request) {
return request.GetHttpContext().Request.UserHostAddress;
}
}
Then, at the API core layer, I know that hosting layer has set the IP address and I can reach it through Properties[ApiCommonRequestKeys.UserHostAddressKey] of HttpRequestMessage instance anytime.
Have a look at this project: https://github.com/tugberkugurlu/PingYourPackage this is a nice ASP.NET Web API project which has been structured in a hosting later agnostic way. May give you a hint.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With