Best Pattern for AllowUnsafeUpdates

前端 未结 6 1612
半阙折子戏
半阙折子戏 2020-12-28 08:54

So far, in my research I have seen that it is unwise to set AllowUnsafeUpdates on GET request operation to avoid cross site scripting. But, if it is required to allow this,

6条回答
  •  星月不相逢
    2020-12-28 08:54

    I would slightly modify Trent's delegate to accept the web to update:

    public static void DoUnsafeUpdate(this SPWeb web, Action action)
    {
        try
        {
            web.AllowUnsafeUpdates = true;
            action(web);
        }
        finally
        {
            web.AllowUnsafeUpdates = false;
        }
    }
    

    And then extend HttpContext to encapsulate verification of the form digest, with an option to elevate using the technique described here:

    public static void DoUnsafeUpdate(this HttpContext context, Action action, bool elevated)
    {
        SPWeb web = SPControl.GetContextWeb(context);
        if (!context.Request.HttpMethod.Equals("POST", StringComparison.Ordinal)
            || web.ValidateFormDigest())
            throw new SPException("Error validating postback digest");
    
        if (elevated)
            web.RunAsSystem(w => w.DoUnsafeUpdate(action));
        else
            web.DoUnsafeUpdate(action);
    }
    

    Usage:

    protected override void OnLoad(System.EventArgs e)
    {
        Context.DoUnsafeUpdate(web =>
        {
            // Update elevated web
        }, true);
    }
    

提交回复
热议问题