Web API 2 RequireHttps允许http连接

2 https asp.net-web-api2

我在我的MVC Web API 2控制器中创建了以下操作:

    [ResponseType(typeof(int))]
    [RequireHttps]
    public IHttpActionResult SaveLead(EcommerceLead lead)
    {
    }
Run Code Online (Sandbox Code Playgroud)

但在我的测试应用程序中,我正在打电话给

http://localhost/api/savelead
Run Code Online (Sandbox Code Playgroud)

它正在发挥作用.是否有任何方法可以使操作仅在通过https调用时才起作用,即如果不是或返回404,则返回404?

Bad*_*dri 11

如果您使用的RequireHttps是Mvc名称空间,则无法使用Web API.您可以自己编写一个简单的Web API过滤器来强制执行HTTPS.由于您使用的是Web API 2,因此请创建一个这样的身份验证过滤器.

public class RequireHttpsAttribute : IAuthenticationFilter
{
    public bool AllowMultiple
    {
        get { return true; }
    }

    public Task AuthenticateAsync(HttpAuthenticationContext context, 
                                        CancellationToken cancellationToken)
    {
        if (context.Request.RequestUri.Scheme != Uri.UriSchemeHttps)
        {
            context.ActionContext.Response = new HttpResponseMessage(
                                    System.Net.HttpStatusCode.Forbidden);

        }
        return Task.FromResult<object>(null);
    }

    public Task ChallengeAsync(HttpAuthenticationChallengeContext context,
                                        CancellationToken cancellationToken)
    {
        return Task.FromResult<object>(null);
    }
}
Run Code Online (Sandbox Code Playgroud)