Require SSL in WebApi?

后端 未结 6 1852
夕颜
夕颜 2020-12-07 15:31

Is there a way to require SSL for WebApi? An attribute?

I don\'t see an applicable attribute under System.Web.Http, something like the RequireHttp

6条回答
  •  春和景丽
    2020-12-07 16:13

    You can use the following code; (automatically redirect to https) redirect to https when an http based request is made.

    To check it in visual studio you need to enable ssl in visual studio. This can be done using enable ssl property to true.

    public class RequireHttpsAttribute: AuthorizationFilterAttribute
    {
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            if(actionContext.Request.RequestUri.Scheme != Uri.UriSchemeHttps)
            {
                // constructing the https url
                var uriBuilder = new UriBuilder(actionContext.Request.RequestUri)
                {
                    Scheme = Uri.UriSchemeHttps,
                    Port = 44353 // port used in visual studio for this 
                };
    
                actionContext.Response.Headers.Location = uriBuilder.Uri;
            }
        }
    }
    

    Use this in Register method like this

    config.Filters.Add(new RequireHttpsAttribute());
    

提交回复
热议问题