asp.net web api 登录未授权

来源:互联网 发布:linux查看io使用率 编辑:程序博客网 时间:2024/04/28 21:56

使用统一的cookie限制访问asp.net web page和asp.net web api,不过当api未授权时,跳转到了登录页面,一堆的html代码不利于被调用端的呈现和识别,故:

1. 添加Attribute: AuthCheckFilter

using Newtonsoft.Json;using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Net.Http;using System.Text;using System.Web;using System.Web.Http.Filters;namespace com.test{    public class AuthCheckFilter : ActionFilterAttribute    {        public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)        {            if (!HttpContext.Current.User.Identity.IsAuthenticated)            {                BaseResponse resp = new BaseResponse() { Code = EReturnCodes.未授权 };                string respJson = JsonConvert.SerializeObject(resp);                byte[] bs = Encoding.UTF8.GetBytes(respJson);                HttpResponseMessage rm = new HttpResponseMessage();                //rm.Headers.Add("Content-Type", "application/json; charset=utf-8"); // 要在下面添加,否则报错                //using (MemoryStream ms = new MemoryStream(bs)) //不能using,否则就丢失了:network error                {                    MemoryStream ms = new MemoryStream(bs);                    rm.Content = new StreamContent(ms);                    rm.Content.Headers.Add("Content-Type", "application/json; charset=utf-8"); // 不能在上面添加,否则报错                }                actionContext.Response = rm;            }            else            {                base.OnActionExecuting(actionContext);            }        }    }}

 

2. 在BaseApiController中添加这个attribute

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Web;using System.Web.Http;using System.Web.Http.Results;namespace com.test{    [AuthCheckFilter]    public class BaseApiController<T> : ApiController        where T : IDisposable, new()    {           }}


 

0 0
原创粉丝点击