asp.net web api-在C#web api中需要HTTPS

本文关键字:HTTPS api C#web net web api- asp | 更新日期: 2023-09-27 18:00:06

如何要求C#apicontrollers使用HTTPS?

我知道我可以在这里添加这样的RequireHTTPSA属性: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))

asp.net web api-在C#web api中需要HTTPS

您可以自己为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);
    }
}