前后端分离的开发中,应用服务需要进行用户身份的验证才允许访问数据。实现的方法很简单。创建一个webapi项目。在App_Start目录下找到WebApiConfig.cs, 在里面增加一个实现类。文章来源:https://www.toymoban.com/news/detail-829874.html
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API 配置和服务
config.Filters.Add(new CustomAuthorize());
// Web API 路由
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
public class CustomAuthorize : AuthorizationFilterAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
//如果用户的Action带有AllowAnonymousAttribute,则不用检测
if (actionContext.ActionDescriptor.GetCustomAttributes<System.Web.Http.AllowAnonymousAttribute>().Any())
{
return;
}
app 接口检测
object au = actionContext.Request.Headers.Authorization;
if (au == null)
{
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized, new { Ret = 4002, Msg = "Token错误!" });
}
else if (!Redis.haskey(au.ToString()))
{
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized, new { Ret = 4008, Msg = "Token超时!" });
}
}
}
}
Controller 类的实现:文章来源地址https://www.toymoban.com/news/detail-829874.html
[RoutePrefix("api/v1")]
public class ValuesController : ApiController
{
[AllowAnonymous] //匿名访问
[Route("getData1"), HttpPost]
public JObject getData1([FromBody] JObject data)
{
return data;
}
//登录访问
[Route("getData2"), HttpPost]
public JObject getData2([FromBody] JObject data)
{
return data;
}
}
到了这里,关于asp.net web api 用户身份验证的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!