MVC授权属性验证JSON值

时间:2013-05-01 09:35:21

标签: asp.net-mvc attributes

我有以下代码,可以正常使用/ Projects / {userId} / {Id}

的网址

但如果我将值发布到/ Projects /和JSON值为

的页面
{"userId":1234,"Id":145}

它不会获取JSON值,UserId和Id都为空。

代码如下

protected override bool AuthorizeCore(HttpContextBase httpContext)
{
    int documentIdfound, userIdFound;
    int? documentId = null;
    var documentIdRoute = httpContext.Request.RequestContext.RouteData.Values["Id"];

    if (int.TryParse((string)documentIdRoute, out documentIdfound))
        documentId = documentIdfound;

    //if we havent found the ProjectId in the RouteData check the querystring. Just in case
    if (documentId == null)
    {
        documentIdRoute = httpContext.Request.QueryString["Id"];
        if (int.TryParse((string)documentIdRoute, out documentIdfound))
            documentId = documentIdfound;
    }

    var userIdRoute = httpContext.Request.RequestContext.RouteData.Values["userId"];

    int.TryParse((string)userIdRoute, out userIdFound);

    var gi = GetCurrentUser();

    try
    {
        var userFound = gi.UserProfiles.Where(x => x.UserId == userIdFound).FirstOrDefault();
        if (userFound != null)
        {
            return gi.IsUserValid(userFound.UserId, documentId.Value);
        }
        else
            return false;
    }
    catch (Exception ex)
    {
        AddErrorToDB(ex);
        return false;
    }
}

1 个答案:

答案 0 :(得分:0)

尝试将参数值作为字符串发送:

{'userId':'1234','Id':'145'}

这将解决问题。