Web API 受權篩選器

方式1、全局認證json

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API 配置和服務
        config.Filters.Add(new ApiAuthorizeAttribute());
    }
}

 

方式2、局部認證app

在控制器前加認證特性[ApiAuthorizeAttribute],方法名前加認證特性ide

[ApiAuthorizeAttribute]
public class ValuesController : ApiController
{
    [Authorize]
    public void Post([FromBody]string value)
    {
    }
}

 如下爲自定義受權篩選器文件code

/// <summary>
/// 受權篩選器
/// </summary>
public class ApiAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool IsAuthorized(HttpActionContext actionContext)
    {
        var tokenHeader = from t in actionContext.Request.Headers where t.Key == "token" select t.Value.FirstOrDefault();
        if (tokenHeader != null)
        {
            string token = tokenHeader.FirstOrDefault();
            if (!string.IsNullOrEmpty(token))
            {
                try
                {
                    return true;
                }
                catch (Exception ex)
                {
                    return false;
                }
            }
        }
        return false;
    }

    /// <summary>
    /// 處理受權失敗的請求
    /// </summary>
    protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
    {
        actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.OK, new
        {
            code = "3001",
            msg = "false",
            data = new { }
        }, "application/json");
    }
}
相關文章
相關標籤/搜索