Reputation: 2646
I've got an Angular (6)
app using .net Web API
w/ Windows Authentication. Both are deployed to the same development web server, which has a valid SSL Certificate.
I'm trying to force an http to https
redirect on all my pages. I've got the Web API
side handled - all the /api
paths to redirect to https
via Kudvenkat's simple tutorial: http://csharp-video-tutorials.blogspot.com/2016/09/aspnet-web-api-enable-https.html
Create a RequireHttpsAttribute.cs class:
using System;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
namespace api
{
public class RequireHttpsAttribute : AuthorizationFilterAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
if (actionContext.Request.RequestUri.Scheme != Uri.UriSchemeHttps)
{
actionContext.Response = actionContext.Request
.CreateResponse(HttpStatusCode.Found);
actionContext.Response.Content = new StringContent
("<p>Use https instead of http</p>", Encoding.UTF8, "text/html");
UriBuilder uriBuilder = new UriBuilder(actionContext.Request.RequestUri);
uriBuilder.Scheme = Uri.UriSchemeHttps;
uriBuilder.Port = 443;
actionContext.Response.Headers.Location = uriBuilder.Uri;
}
else
{
base.OnAuthorization(actionContext);
}
}
}
}
WebApiConfig.cs:
public static void Register(HttpConfiguration config)
{
config.Filters.Add(new RequireHttpsAttribute());
}
But as far as Angular routes (routes that don't look like https://myurl.com/api
, but instead look like https://myurl.com/index.html#
), I can't get these to redirect to https
. Is it normal to have to specify http to https
redirects both in the Web API
code and in the Angular
code?
If not, perhaps we need to configure our webserver to only use https
?
Upvotes: 1
Views: 5369
Reputation: 15144
I do it by using a URL rewrite in web.config, like below:
<system.webServer>
<rewrite>
<rules>
<rule name="HTTPS" stopProcessing="true">
<match url="(.*)" />
<conditions>
<add input="{HTTPS}" pattern="off" ignoreCase="true" />
</conditions>
<action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Permanent" appendQueryString="false" />
</rule>
</rules>
</rewrite>
</system.webServer>
This should handle both WebApi and MVC/HTML/etc.
Upvotes: 1