我無法弄清楚如何在Web API中使用來自System.Web.Http.Filters的IAuthorizationFilter實現授權過濾器。在Web API中正確實現IAuthorizationFilter
這是一個簡單的過濾器我寫信給所有非HTTPS請求一個403禁止訪問響應響應:
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();
}
}
我所寫的,到目前爲止運行,但是當我嘗試過定期訪問API http,它只是掛起,我從來沒有得到迴應。
http://aspnet.codeplex.com/sourcecontrol/latest#Samples/WebApi/BasicAuthentication/ReadMe.txt – Ali