Last active
May 14, 2016 11:23
-
-
Save rmacfie/7ed1d3a5c0775c7834c449d0ec538758 to your computer and use it in GitHub Desktop.
Enforce domain name in Asp.Net Core
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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