在C#Web API中需要HTTPS

时间:2014-04-25 02:22:48

标签: c# asp.net-web-api

如何为C#apicontrollers申请HTTPS?

我知道我可以在这里添加一个RequireHTTPSAttribute:http://www.asp.net/web-api/overview/security/working-with-ssl-in-web-api但这只是在响应中添加了“HTTPS Required”。

我宁愿让它做的是在屏幕上输出json,上面写着“HTTPS Required”,而不仅仅是在响应标题上。

这可能吗?

修改

这就是我提出的,是否有一种更优雅的方式,所以我减少了重复的代码。

        ResultWrapper<Temp> wrapper = new ResultWrapper<Temp>(Request);

        if (Request.RequestUri.Scheme != Uri.UriSchemeHttps)
        {
            wrapper.Error = "Https is Required";
        }
        else
        {
            wrapper.RequestUrl = Request.RequestUri.ToString();

            wrapper.Results.Url = "http://www.google.com";
        }

        return wrapper;

第二次修改

我找到了一种更好的方法,你可以编辑在响应中发回的内容流,然后发送回你想要序列化为Json的任何类,如下所示:

 Content = new StringContent(Json.Encode(wrapper))

1 个答案:

答案 0 :(得分:2)

您可以自己编写一个简单的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);
    }
}