Require SSL in WebApi?

后端 未结 6 1912
夕颜
夕颜 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:07

    After some research I determined this is probably the most appropriate response. It could be updated to provide json, text, or xml despite the specification indicating Html is recommended.

    public class RequireHttpsAttribute : AuthorizationFilterAttribute
    {
        public override void OnAuthorization(HttpActionContext context)
        {
            if (context.Request.RequestUri.Scheme != Uri.UriSchemeHttps)
            {
                context.Response = new HttpResponseMessage(HttpStatusCode.UpgradeRequired);
                context.Response.Headers.Add("Upgrade", "TLS/1.1, HTTP/1.1");
                context.Response.Headers.Add("Connection", "Upgrade");
                context.Response.Headers.Remove("Content-Type");
                context.Response.Headers.Add("Content-Type", "text/html");
                context.Response.Content = new StringContent("

    Http protocol is not valid for this service call.

    Please use the secure protocol https.

    "); } else base.OnAuthorization(context); } }

    Here is the specification: RFC 2817

提交回复
热议问题