Skip to content

Instantly share code, notes, and snippets.

@rmacfie
Last active May 14, 2016 11:23
Show Gist options
  • Save rmacfie/7ed1d3a5c0775c7834c449d0ec538758 to your computer and use it in GitHub Desktop.
Save rmacfie/7ed1d3a5c0775c7834c449d0ec538758 to your computer and use it in GitHub Desktop.
Enforce domain name in Asp.Net Core
using System;
namespace Microsoft.AspNet.Builder
{
public static class DomainEnforcer
{
public static IApplicationBuilder UseDomainEnforcer(this IApplicationBuilder app, string domainToEnforce)
{
if (string.IsNullOrEmpty(domainToEnforce))
throw new ArgumentNullException(nameof(domainToEnforce));
Func<RequestDelegate, RequestDelegate> middleware = next => async context =>
{
var req = context.Request;
var res = context.Response;
if (req.Host.HasValue && req.Host.Value == domainToEnforce)
await next(context);
else
res.Redirect($"{req.Scheme}://{domainToEnforce}{req.Path}{req.QueryString}");
};
return app.Use(middleware);
}
}
}
namespace MyProject
{
public class Startup
{
public void Configure(IApplicationBuilder app)
{
app.UseDomainEnforcer("example.com");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment