2012-03-01 74 views
27

內的動作參數值我有我從jQuery的發佈到一個動作:獲得一個動作過濾器

[HttpPost] 
public void UpdateGroupName(int groupId, string name) 
{ 
    authorisationRepository.UpdateGroupName(groupId, name); 
} 

也能正常工作與groupIdname。我還有其他一些小組操作,因此我想使用授權屬性來確保執行更改的人員有權進行更改。

我已經有一個AuthorizationAttribute,通過訪問filterContext.HttpContext.Request.Params["groupId"]在GET請求上成功檢索groupId,但是當談到POST時,它不起作用。 Request.Form是空的,Request.Params也是空的。

下面是我在我的授權屬性代碼:

public int groupId { get; set; } 

protected override bool AuthorizeCore(HttpContextBase httpContext) 
{ 
    username = httpContext.User.Identity.Name.Split('\\').Last(); 

    // awesome permissions checking goes here... 

    return authorized; 
} 

public override void OnAuthorization(AuthorizationContext filterContext) 
{ 
    groupId = int.Parse(filterContext.HttpContext.Request.Params["groupId"]); // this line throws an exception 
    base.OnAuthorization(filterContext); 
} 

我已經看過這個answer但我Form屬性爲空:(

更新,以顯示jQuery的崗位:

var serverComm = { 
    post: function (url, data) { 
     return $.ajax({ 
      url: url, 
      type: 'POST', 
      contentType: 'application/json; charset=utf-8', 
      data: JSON.stringify(data) 
     }); 
    }, 
    get: function (url, data) { 
     return $.ajax({ 
      url: url, 
      type: 'GET', 
      cache: false, 
      contentType: 'application/json; charset=utf-8', 
      data: data 
     }); 
    } 
}; 
// some awesome code later... 
serverComm.post(editGroupNameUrl, { groupId: group.id, name: newName }) 
+0

而參數是Form參數嗎?有沒有機會在QueryString上? – ivowiblo 2012-03-01 15:28:31

+0

QueryString爲空。你是什​​麼意思「是形式參數」?您可以在頂部代碼示例 – soniiic 2012-03-01 15:32:07

+0

中看到我的操作,您可以發佈表單代碼嗎? – ivowiblo 2012-03-01 15:34:14

回答

42

你的代碼不工作的原因是因爲你正在發送你的請求作爲JSON字符串。因此,POST正文中沒有請求參數,您無法在Request.Params中獲取它們。

所以不是:

filterContext.HttpContext.Request.Params["groupId"] 

使用:

filterContext.Controller.ValueProvider.GetValue("groupId").AttemptedValue 

這將查詢值提供商(你的情況JsonValueProvider)來獲取客戶端發送相應的值。

+0

它將在authorizeattribute中工作嗎? – Dragon 2017-04-17 12:56:36

1

嘗試沒有stringify我猜MVC是除了請求參數 - >動作參數理解另一種綁定方式。它是瞭解json發佈的。 JQuery,如果你傳遞數據對象(沒有stringify)將發佈每個字段作爲請求參數(至少,我認爲是這樣)。這很容易嘗試:)