WebApi的自定义Filter

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;

namespace WebAPIFilterTest1
{
    public class MyAutorFilter : IAuthorizationFilter
    {
        public bool AllowMultiple => true;
        public async Task<HttpResponseMessage> ExecuteAuthorizationFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation)
        {
            IEnumerable<string> userNames;
           if(! actionContext.Request.Headers.TryGetValues("UserName", out userNames))
            {
                return new HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
            }
            string userName = userNames.First();
            if (userName=="admin")
            {
                return await continuation();
            }
            else
            {
                return new HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
            }

        }
    }
}
MyAutorFilter
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;

namespace WebAPIFilterTest1
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API 配置和服务

            // Web API 路由
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            config.Filters.Add(new MyAutorFilter());
        }
    }
}
WebApiConfig

 

posted on 2017-11-29 15:20  愚公学编程  阅读(656)  评论(0)    收藏  举报