作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
使用基本身份验证和 asp.net Web-Api,其中 JSON 获取/发布到我的 API,我需要检查用户名/密码是否存在于成员资格表中。下面的代码是做什么的:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Security;
namespace MvcApplication4.Filter
{
public class BasicAuthenticationAttribute : System.Web.Http.Filters.ActionFilterAttribute
{
public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
{
if (actionContext.Request.Headers.Authorization == null)
{
actionContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
}
else
{
string authToken = actionContext.Request.Headers.Authorization.Parameter;
string decodedToken = Encoding.UTF8.GetString(Convert.FromBase64String(authToken));
string username = decodedToken.Substring(0, decodedToken.IndexOf(":"));
string password = decodedToken.Substring(decodedToken.IndexOf(":") + 1);
if (Membership.Provider.ValidateUser(username, password))
{
// User exists in the membership table
}
else
{
// User doesn't exist - so return Unathorized
actionContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
}
}
}
}
}
public class ApiMembers
{
public int id { get; set; }
public string UserName { get; set; }
public int car_id { get; set; }
}
[BasicAuthentication]
public IEnumerable<Cars> GetCars(long id)
{
var auth = dba.ApiMembers.Select(a => a.car_id == id && a.UserName=***AuthorisedUserName***).FirstOrDefault();
if (auth == null || !auth.Any())
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.Unauthorized));
}
else
{
// User exists in table, so give them info on car
}
最佳答案
您可以设置当前主体:
if (Membership.Provider.ValidateUser(username, password))
{
// User exists in the membership table
var identity = new GenericIdentity(username);
Thread.CurrentPrincipal = new GenericPrincipal(identity, null);
}
Request.GetPrincipal
扩展方法)。
[BasicAuthentication]
public HttpResponseMessage Get()
{
string username = User.Identity.Name;
...
}
关于asp.net - 如何在其他 Controller 中使用授权用户名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11135473/
我是一名优秀的程序员,十分优秀!