c# - 如何在 AuthorizeAttribute ASP.NET Web.API MVC 5 的 IsAuthorized 上获取 Post 参数

标签 c# asp.net asp.net-mvc asp.net-web-api2

我需要在授权时获取我的帖子参数的值。网络上的搜索者但没有解决方案有效。 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;
    }        
}

Controller 中的代码-

[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;
    }        
}

关于c# - 如何在 AuthorizeAttribute ASP.NET Web.API MVC 5 的 IsAuthorized 上获取 Post 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42664029/

相关文章:

javascript - Ajax.BeginForm OnSuccess、onBegin、OnFailure 未触发

c# - 在 ASP.Net MVC 中创建异步报告

c# - 使用 ModelMetadata 获取完整的属性名称

c# - ASP.NET MVC @Html.LabelFor(model => model.Name) 助手

C# : Dealing with HttpWebResponse timeout problems

c# - 继承属性

c# - 无法使用 Unity 解析的类型 [MVC 5]

css - ASP.Net 菜单控件在选择子菜单项时不突出显示父菜单

c# - 在 ASP MVC 中测试 Controller

c# - IIS 和 asp.net appcmd