Web Api with web hosting and self-hosting

Is there a best practice for supporting self and web hosting (at the same time)?

There are many problems I had to solve. In self-service, autofac does not work properly because HttpContext.Current is not installed and GlobalConfiguration is not available for self-hosting.

Are there other issues to be aware of?

+3


source to share


3 answers


Have a look at this answer: fooobar.com/questions/1133778 / ... This shows you how you can structure your solution at the hosting level agnostically.

Basically, add the ASP.NET API logic to a separate project and as @DarrelMiller suggested, don't use any specific hosting context in that project. Don't even link to unnecessary assemblies (eg :) System.Web

inside this project. However, you will have certain needs in the hosting layer, such as getting the consumer's IP address (this cannot be done through what the ASP.NET Web API gives you). In such cases, use some kind of contract between your main API and the hosting tiers.

For example, below one is a message handler that will set the consumer IP for every request and I have 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 core API level, I know that an IP address is set at the hosting level and I can get it through the Properties[ApiCommonRequestKeys.UserHostAddressKey]

instance HttpRequestMessage

at any time.

Take a look at this project: https://github.com/tugberkugurlu/PingYourPackage is a nice ASP.NET Web API project that has been structured on hosting in a later agnostic way. May give you a hint.

+6


source


You shouldn't be using HttpContext.Current in any web API project. Everything you need should be in HttpRequestMessage.Properties. I don't know any problem with DI using Self-host, I know you can use Unity in Self-host without any problem.



+4


source


WebAPI has a different pipeline and they use HTTPHandler. which is at a lower level. Hence, using HTTPContext.Current is not a good idea.

0


source







All Articles