簡體   English   中英

ASP.net MVC 3 - 在OnActionExecuting中發布JSON數據

[英]ASP.net MVC 3 - Getting posted JSON data in OnActionExecuting

我使用jquery中的$ .ajax方法將數據發布到肌動蛋白,指定要使用數據字段發布的數據以傳遞JSON字符串化值。

這些被發布到操作OK但我無法在OnActionExecuting操作過濾器中獲取它們(它們不是Forms或Params集合的一部分)。 有沒有辦法得到它們,如果沒有,你能告訴分享為什么不呢?

如果您的操作采用模型:

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

postingData變量包含發送到操作的JSON格式的數據

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM