0

I'm trying to delete an object from a bucket. Reading the docs it all sounds super simple, but I just can't seem to get it working. On the server side I have the following in ASP.NET:

[HttpDelete]
[Route("api/forge/oss/objects/delete")]
public async Task<dynamic> DeleteObject_fromBucket()
{
    // basic input validation
    HttpRequest req = HttpContext.Current.Request;

    if (string.IsNullOrWhiteSpace(req.Params["bucketKey"]))
        throw new System.Exception("BucketKey parameter was not provided.");

    if (string.IsNullOrWhiteSpace(req.Params["objectName"]))
        throw new System.Exception("ObjectName parameter was not provided."); 

    string bucketKey = req.Params["bucketKey"];
    string objectName = req.Params["objectName"];

    // call API to delete object on the bucket
    dynamic oauth = await OAuthController.GetInternalAsync();
    ObjectsApi objects = new ObjectsApi();
    string access_token = oauth.access_token; ;
    objects.Configuration.AccessToken = access_token;

    // delete the file/object
    await objects.DeleteObjectAsync(bucketKey, objectName);
    return 0;
}

The client side:

function deleteObject(node) {
    result = window.confirm('Wollen Sie dieses Modell löschen');
    if (result == false) { return; }
    else {
        var bucketKey = node.parents[0];
        var objectName = node.text;

        var formData = new FormData();
        formData.append('bucketKey', bucketKey);
        formData.append('objectName', objectName);

        $.ajax({
            url: 'api/forge/oss/objects/delete',
            data: formData,
            contentType: false,  
            processData: false,
            type: 'DELETE',  // man könnte auch method: schreiben
            success: function (data) {
                $('#appBuckets').jstree(true).refresh_node(node);
            }
        });
    }       
}

I always get the exception that it fails to make API call. The bucketKey and objectName are both Strings. Could anyone help me understand where I'm going wrong?

Thanks a lot.

dda
  • 6,030
  • 2
  • 25
  • 34
dabuchera
  • 79
  • 5

2 Answers2

1

I happened to make a working code for one attendee in Sydney Accelerator this week. The code snippet is tested on Learn Forge Tutorial (2 legged workflow). One is deleting bucket, the other is deleting object. It looks you are also testing with that skeleton of tutorial?

I made a similar code like yours at the beginning, but my VS threw error when compiling. Finally, I found it is due to the return value. Since it is a HTTP Request, it looks 0 does not make sense to a response. In addition, the default scope of the internal token in that tutorial does not contain bucket delete and data write (for deleting object). I got the detail error with the response of client side.

After adding those scopes at OAuthController.cs. All started to work:

 public static async Task<dynamic> GetInternalAsync()
 {
  if (InternalToken == null || InternalToken.ExpiresAt < 
   DateTime.UtcNow)
  {
    InternalToken = await Get2LeggedTokenAsync(new Scope[] { 
       Scope.BucketCreate, Scope.BucketRead, Scope.DataRead, 
       Scope.DataCreate,Scope.BucketDelete,Scope.DataWrite});
        InternalToken.ExpiresAt = 
    DateTime.UtcNow.AddSeconds(InternalToken.expires_in);
  }

  return InternalToken;
}

If these are not helpful for your case, I'd suggest building the Forge SDK source project, adding to your project, and debugging the corresponding methods to see what the exact error is. Please feel free to let us know if you have any questions on this.

Server Side:

    [HttpPost]
    [Route("api/forge/oss/buckets/delete")]
    public async Task<dynamic> DeleteBucket([FromBody]CreateBucketModel bucket)
    {
        BucketsApi buckets = new BucketsApi();
        dynamic token = await OAuthController.GetInternalAsync();
        buckets.Configuration.AccessToken = token.access_token; 

        await buckets.DeleteBucketAsync(bucket.bucketKey); 
        //or
        //buckets.DeleteBucket(bucket.bucketKey); 

        return Task.CompletedTask;
    }

    [HttpPost]
    [Route("api/forge/oss/objects/delete")]
    public async Task<dynamic> DeleteObject([FromBody]DeleteObjectModel 
                                                      objInfo)
    {
        ObjectsApi objs = new ObjectsApi();
        dynamic token = await OAuthController.GetInternalAsync();
        objs.Configuration.AccessToken = token.access_token;

        await objs.DeleteObjectAsync(objInfo.bucketKey, objInfo.objectKey);

        //or
        //objs.DeleteObject(objInfo.bucketKey, objInfo.objectKey); 

        return Task.CompletedTask;
    }

    public class CreateBucketModel
    {
      public string bucketKey { get; set; }
    }

    public class DeleteObjectModel
    {
       public string bucketKey { get; set; }
       public string objectKey { get; set; } 
     }

Client Side:

function deleteBucket() {
     //select one bucket node of the tree
     var bucketKey = $('#appBuckets').jstree(true).get_selected(true)[0].id;

     var policyKey = $('#newBucketPolicyKey').val();
     jQuery.post({
        url: '/api/forge/oss/buckets/delete',
             contentType: 'application/json',
             data: JSON.stringify({ 'bucketKey': bucketKey, 
                                    'policyKey': policyKey }),
             success: function (res) {
               $('#appBuckets').jstree(true).refresh();
               alert('Bucket  deleted') 
              },
             error: function (err) {
               alert('Bucket not deleted')
               console.log(err);
             }
         });
     }

   function deleteObject() {
      //assume the first selected tree node is bucket
      var bucketKey = $('#appBuckets').jstree(true).get_selected(true)[0].text;
      //assume the second selected tree node is object
      var objectKey = $('#appBuckets').jstree(true).get_selected(true)[1].text;
      jQuery.post({
          url: '/api/forge/oss/objects/delete',
          contentType: 'application/json',
          data: JSON.stringify({ 'bucketKey': bucketKey, 
                                 'objectKey': objectKey }),
          success: function (res) {
             $('#appBuckets').jstree(true).refresh();
             alert('Object  deleted') 
          },
          error: function (err) {
            alert('Object not deleted')
            console.log(err);
          }
      });
 }
Xiaodong Liang
  • 2,051
  • 2
  • 9
  • 14
0

URL should be url: '/api/forge/oss/objects/delete' instead of url: 'api/forge/oss/objects/delete'

  • Not necessarily. If the application is not at the domain root your suggestion would fail. If it is there, it would not make any difference. – PepitoSh Jul 13 '18 at 06:17