我在使用System.Web.Http.Filters中的IAuthorizationFilter来解决如何在Web API中实现授权过滤器时遇到了麻烦.
这是一个简单的过滤器,我写的是为了响应所有带有403禁止响应的非https请求:
public class HttpsFilter : IAuthorizationFilter {
public bool AllowMultiple {
get {
return false;
}
}
public Task<HttpResponseMessage> ExecuteAuthorizationFilterAsync( HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation ) {
var request = actionContext.Request;
if ( request.RequestUri.Scheme != Uri.UriSchemeHttps ) {
HttpResponseMessage response = request.CreateResponse( HttpStatusCode.Forbidden );
response.Content = new StringContent( "<h1>HTTPS Required</h1>", Encoding.UTF8, "text/html" );
actionContext.Response = response;
return new Task<HttpResponseMessage>( delegate() {
return response;
} );
}
else
return continuation();
}
}
Run Code Online (Sandbox Code Playgroud)
我到目前为止所写的内容已经运行,但是当我尝试通过常规http访问api时,它只是挂起而且我从来没有得到过响应.