[英]How to get Post parameters on IsAuthorized of AuthorizeAttribute ASP.NET Web.API MVC 5
我需要在授權時獲取我的帖子參數的值。 網絡上的搜索者但沒有解決方案正在運作。 ActionArguments
計數始終顯示0並且無法在ActionDescriptor.GetParameters()
查找值
這是我的代碼:
POST模型 -
public class XyzModel
{
public int Prop1 { get; set; }
public string Prop2 { get; set; }
}
自定義授權屬性 -
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
protected override bool IsAuthorized(HttpActionContext actionContext)
{
bool conditions = // here I need to check value of my model (XyzModel) properties
if(conditions)
{
return true;
}
return false;
}
}
控制器中的代碼 -
[HttpPost]
[CustomAuthorizeAttribute]
public IHttpActionResult MyAction(XyzModel model)
{
// my work here
}
有什么建議嗎?
您可以訪問ActionArguments的模型屬性,它將返回XyzModel對象。 您可以對其屬性執行任何操作:
XyzModel model = (XyzModel)actionContext.ActionArguments["model"];
在你的代碼中它將是這樣的:
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
protected override bool IsAuthorized(HttpActionContext actionContext)
{
var prop1 = HttpContext.Current.Request.Params["Prop1"];
var prop2 = HttpContext.Current.Request.Params["Prop2"];
bool conditions = // add conditions based on above properties
if(conditions)
{
return true;
}
return false;
}
}
我相信,你不會在AuthorizeAttribute
獲得post參數值,因為在action的參數綁定之前調用AuthorizeAttribute
方法。
對於您的方案,您可以使用僅在操作的參數綁定后執行的ActionFilterAttribute
。 您可以使用ActionFilterAttribute
創建自定義過濾器屬性
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
public class CheckMyPostDataFilter : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
XyzModel model = (XyzModel )actionContext.ActionArguments["model"]; // you will get data here
base.OnActionExecuting(actionContext);
}
}
您可以在操作中簡單地在CheckMyPostDataFilter
過濾器上方CheckMyPostDataFilter
裝飾:
[HttpPost]
[CheckMyPostData]
public IHttpActionResult MyAction(XyzModel model)
{
// my work here
}
您可以使用Request Body Input Stream來讀取整個Body內容,如下所示
public sealed class CustomAuthorizeAttribute : AuthorizeAttribute
{
protected override bool IsAuthorized(HttpActionContext actionContext)
{
var req = HttpContext.Current.Request.InputStream;
string body = new StreamReader(req).ReadToEnd();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.