.net 在 WebApi 中需要 SSL?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11265710/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 16:30:29  来源:igfitidea点击:

Require SSL in WebApi?

.netsslasp.net-web-api

提问by EBarr

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

有没有办法为 WebApi 要求 SSL?一个属性?

I don't see an applicable attribute under System.Web.Http, something like the RequireHttpsattribute we have for MVC. I'm just trying to avoid rolling my own attribute/ message handler if there is a built in solution.

我在 下没有看到适用的属性System.Web.Http,类似于RequireHttps我们为 MVC 设置的属性。如果有内置解决方案,我只是想避免滚动我自己的属性/消息处理程序。

采纳答案by Teoman Soygul

You can use the RequireHttpsHandlerfrom WebAPIContrib project. Basically, all it does is to check the incoming request URI scheme:

您可以使用WebAPIContrib 项目中的RequireHttpsHandler。基本上,它所做的只是检查传入的请求 URI 方案:

if (request.RequestUri.Scheme != Uri.UriSchemeHttps)
{
  // Forbidden (or do a redirect)...
}

Alternately, Carlos Figueira has another implementationon his MSDN blog.

或者,Carlos Figueira在他的 MSDN 博客上有另一个实现

回答by The Light

public class RequireHttpsAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        if (actionContext.Request.RequestUri.Scheme != Uri.UriSchemeHttps)
        {
            actionContext.Response = new HttpResponseMessage(HttpStatusCode.Forbidden);
        }
    }
}

回答by Adrian Toman

It is puzzling that there is no equivalent to the ASP.NET MVC RequireHttps attribute in ASP.NET Web API. However you can easily create one based on RequireHttpsfrom MVC.

令人费解的是,在 ASP.NET Web API 中没有与 ASP.NET MVC RequireHttps 属性等效的属性。但是,您可以轻松地基于MVC 中的RequireHttps创建一个。

using System;
using System.Net.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;

...

public class RequireHttpsAttribute : AuthorizationFilterAttribute
{
    public override void OnAuthorization(HttpActionContext actionContext)
    {
        if (actionContext == null)
        {
            throw new ArgumentNullException("actionContext");
        }

        if (actionContext.Request.RequestUri.Scheme != Uri.UriSchemeHttps)
        {
            HandleNonHttpsRequest(actionContext);
        }
        else
        {
            base.OnAuthorization(actionContext);
        }
    }

    protected virtual void HandleNonHttpsRequest(HttpActionContext actionContext)
    {
        actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden);
        actionContext.Response.ReasonPhrase = "SSL Required";
    }
}

All that there is left to do is to argue about how much redundant code there is.

剩下要做的就是争论有多少冗余代码。

回答by Amjad Husseini

you can use the following filter class to force your action method to use SSL, this will handle your request wither its a GET method or any other verb, if its a get method it will redirect the browser (using the location header) to the new URI. Otherwise a message will be shown to use https

您可以使用以下过滤器类来强制您的操作方法使用 SSL,这将通过 GET 方法或任何其他动词处理您的请求,如果它是一个 get 方法,它会将浏览器(使用位置标头)重定向到新的URI。否则将显示一条消息使用 https

Below code shows that you have to override OnAuthorization method after inheriting from AuthorizationFilterAttribute.

下面的代码显示您必须在从 AuthorizationFilterAttribute 继承之后覆盖 OnAuthorization 方法。

        string _HtmlBody = string.Empty;
        UriBuilder httpsNewUri;

        var _Request = actionContext.Request;

        if (_Request.RequestUri.Scheme != Uri.UriSchemeHttps )
        {

            _HtmlBody = "<p>Https is required</p>";

            if (_Request.Method.Method == "GET"){

                actionContext.Response = _Request.CreateResponse(HttpStatusCode.Found);
                actionContext.Response.Content = new StringContent(_HtmlBody, Encoding.UTF8, "text/html");

                httpsNewUri = new UriBuilder(_Request.RequestUri);
                httpsNewUri.Scheme = Uri.UriSchemeHttps;
                httpsNewUri.Port = 443;

                //To ask a web browser to load a different web page with the same URI but different scheme and port
                actionContext.Response.Headers.Location = httpsNewUri.Uri;


            }else{

                actionContext.Response = _Request.CreateResponse(HttpStatusCode.NotFound);
                actionContext.Response.Content = new StringContent(_HtmlBody, Encoding.UTF8, "text/html");

            }
}

回答by Nayas Subramanian

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

您可以使用以下代码;(自动重定向到 https)在发出基于 http 的请求时重定向到 https。

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

要在 Visual Studio 中检查它,您需要在 Visual Studio 中启用 ssl。这可以通过使用 enable ssl 属性为 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());

回答by N-ate

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.

经过一些研究,我确定这可能是最合适的回应。尽管规范表明建议使用 Html,但它可以更新以提供 json、text 或 xml。

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("<html><head></head><body><h1>Http protocol is not valid for this service call.</h1><h3>Please use the secure protocol https.</h3></body></html>");
        }
        else base.OnAuthorization(context);
    }
}

Here is the specification: RFC 2817

这是规范:RFC 2817