正在读取ASP.NET WEB API中的每个传入请求(URL)
本文关键字:请求 URL ASP 读取 NET WEB API | 更新日期: 2023-09-27 18:20:23
我使用的是ASP.NET MVC
框架。在这个框架中,我们检查了每个传入请求(url)中的某个键,并将其分配给一个属性。我们创建了一个自定义类,它派生自CCD_;我们覆盖OnActionExecuting()
以提供我们的自定义逻辑。
我们如何在ASP.NET WEB API中实现相同的功能
//Implementation from ASP.NET MVC
public class ApplicationController : Controller
{
public string UserID { get; set; }
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (!string.IsNullOrEmpty(Request.Params["uid"]))
UserID = Request.Params["uid"];
base.OnActionExecuting(filterContext);
}
}
我在ASP.NET WEB API中尝试了什么:尽管这是有效的,但我想知道这是否是正确的方法?
创建了一个基本控制器
public class BaseApiController : ApiController
{
public string UserID { get; set; }
}
创建了另一个继承ActionFilterAttribute类的类&我覆盖OnActionExecuting()
public class TokenFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
{
var queryString = actionContext.Request.RequestUri.Query;
var items = HttpUtility.ParseQueryString(queryString);
var userId = items["uid"];
((MyApi.Data.Controllers.BaseApiController)(actionContext.ControllerContext.Controller)).UserID = userId;
}
}
现在注册这个类
public static void Register(HttpConfiguration config)
{
config.Filters.Add(new TokenFilterAttribute());
}
您可以使用ASP.NET Web API中的消息处理程序。这是一种典型的安全场景,当您需要从查询字符串、URL或HTTP标头中获取一些用户令牌时
http://www.asp.net/web-api/overview/advanced/http-message-handlers
1.当你只需要从URL中提取userId,然后将其用作Api方法的参数,ASP.NET WebAPI就会为你工作,就像一样
[HttpGet, Route("{userId}/roles")]
public UserRoles GetUserRoles(string userId, [FromUri] bool isExternalUser = true)
它适用于这样的请求
http://.../15222/roles?isExternalUser=false
2.如果是安全场景,请参阅http://www.asp.net/web-api/overview/security/authentication-and-authorization-in-aspnet-web-api基本上,您将需要一些MessageHandler,或者您也可以使用过滤器属性,这是ASP.NET Web API中的机制来拦截每个调用。
如果您需要处理每个请求,那么MessageHandler就是您的方法。你需要实现MessageHanler,然后注册它。
简单地说,典型的MessageHandler是从MessageHandler或DelegatingHandler派生的类,具有SendAsync方法overriden:
class AuthenticationHandler : DelegatingHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
// Your code here
return base.SendAsync(request, cancellationToken);
}
}
And you need register it
static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Other code for WebAPI registerations here
config.MessageHandlers.Add(new AuthenticationHandler());
}
}
并从Global.asax.cs 调用
WebApiConfig.Register(GlobalConfiguration.Configuration);
这类处理程序的一些伪合成实现示例(在这里,您需要从IPrincipal中实例化UidPrincipal,从IIdentity中实例化UidIdentity)
public class AuthenticationHandler : DelegatingHandler
{
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
try
{
var queryString = actionContext.Request.RequestUri.Query;
var items = HttpUtility.ParseQueryString(queryString);
var userId = items["uid"];
// Here check your UID and maybe some token, just dummy logic
if (userId == "D8CD2165-52C0-41E1-937F-054F24266B65")
{
IPrincipal principal = new UidPrincipal(new UidIdentity(uid), null);
// HttpContext exist only when hosting as asp.net web application in IIS or IISExpress
if (HttpContext.Current != null)
{
HttpContext.Current.User = principal;
}
else
{
Thread.CurrentPrincipal = principal;
}
return base.SendAsync(request, cancellationToken);
}
catch (Exception ex)
{
this.Log().Warn(ex.ToString());
return this.SendUnauthorizedResponse(ex.Message);
}
}
else
{
return this.SendUnauthorizedResponse();
}
}
catch (SecurityTokenValidationException)
{
return this.SendUnauthorizedResponse();
}
}
}
并允许从某些ASP.NET WebApi方法或WebApi类中的某些属性访问它
var uid = ((UidIdentity)User.Identity).Uid