在jQuery中使用$ .ajax方法將數據發佈到actin,指定要使用數據字段發佈的數據以傳遞JSON字符串化值。ASP.net MVC 3 - 在OnActionExecuting中獲取發佈的JSON數據
這些張貼到行動確定,但我不能讓他們在一個OnActionExecuting行動過濾器(他們不是形式或參數集合的一部分)。有沒有辦法讓他們,如果沒有,你能告訴分享爲什麼不呢?
在jQuery中使用$ .ajax方法將數據發佈到actin,指定要使用數據字段發佈的數據以傳遞JSON字符串化值。ASP.net MVC 3 - 在OnActionExecuting中獲取發佈的JSON數據
這些張貼到行動確定,但我不能讓他們在一個OnActionExecuting行動過濾器(他們不是形式或參數集合的一部分)。有沒有辦法讓他們,如果沒有,你能告訴分享爲什麼不呢?
如果你的動作發生的模型:
[HttpPost]
public ActionResult About(SomeViewModel model)
{
return Json(model);
}
,你可以直接在此參數的值,因爲JsonValueProviderFactory早就解析它:
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
SomeViewModel model = filterContext.ActionParameters["model"] as SomeViewModel;
}
如果沒有模型(爲什麼不有嗎?)您可以從請求流中讀取JSON:
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
filterContext.HttpContext.Request.InputStream.Position = 0;
using (var reader = new StreamReader(filterContext.HttpContext.Request.InputStream))
{
string json = reader.ReadToEnd();
}
}
protected override void OnActionExecuting(ActionExecutingContext ctx) {
//All my viewDto end with "viewDto" so following command is used to find them
KeyValuePair<string, object> dto = ctx.ActionParameters.FirstOrDefault(item =>
item.Key.ToLower().EndsWith("viewdto")
);
string postedData;
if (dto.Key != null) {
object viewData = dto.Value;
if (dto.Key.ToLower() == "viewdto") {
var stdStoryViewDto = dto.Value as StandardStoryViewDto;
//removing unnecessary stuff
stdStoryViewDto.Industries.Clear();
stdStoryViewDto.TimeZones.Clear();
viewData = stdStoryViewDto;
}
postedData = JsonConvert.SerializeObject(viewData);
} else {
postedData = string.Join(",",
Array.ConvertAll(ctx.ActionParameters.Keys.ToArray(),
key => key + "=" + ctx.ActionParameters[key])
);
}
}
postedData變量包含發送到動作
感謝達林,在這種 – 2011-02-23 22:02:09
@Steve Ward在JSON格式的數據,你要問你的意見的東西嗎?有沒有不清楚我的答案? – 2011-02-23 22:04:49
謝謝Darin。在這種情況下,此參數不是模型的一部分,因爲它被提供給每個動作,但從未被動作使用(與認證相關)。它只是用在全局動作過濾器中,所以第二種方法似乎是要走的路。我可以解析出來的JSON,因爲這似乎是唯一的方法去... – 2011-02-23 22:11:12