我很难弄清楚如何使用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();
}
}到目前为止,我写的东西都在运行,但是当我试图通过常规的http访问api时,它就挂起了,而且我从来没有得到过响应。
发布于 2013-04-13 03:10:32
在返回任务之前,您需要将任务保存到变量中并调用task.Start()方法,或者使用Task<HttpResponseMessage>.Factory.StartNew(Action action)方法创建任务。
发布于 2013-04-13 03:19:58
对于您的场景,您可以简单地从"System.Web.Http.AuthorizeAttribute“派生。
示例:
public class HttpsFilterAttribute : System.Web.Http.AuthorizeAttribute
{
public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
{
//do something
}
}https://stackoverflow.com/questions/15978999
复制相似问题