How to integrate Web API ?

Estimated reading: 2 minutes 387 views

How to integrate and refer Visual Guard Assembly Reference in your WEB API application

Note Note
To integrate Visual Guard in your WEB API Application project, kindly refer How to integrate Visual Guard in your MVC application to give assembly reference
and configure web.config.

Securing Controller/Action


Using VGAuthorize attribute

Note Note
While mentioning the permission in the ‘VGAuthorize’ attribute, please take the full name of the permission (along with full path).   Example: “ReadOnly” permission exist in folder “Auditors”, hence, full name of the permission is : “/Auditors/ReadOnly”
 [VGAuthorize(Roles = "Admin")]
 public class ProductionController : ApiController
 {
     Product[] products = new Product[]
     {
     new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 },
     new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M },
     new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M }
     };

     [VGAuthorize(Permissions = "CanGetAllRoles", Roles = "RoleManager")]
     public IEnumerable<Product> GetAllProducts()
     {
         return products;
     }

     [VGAuthorize(Permissions = "ReadOnly")]
     [VGAuthorize(Permissions = "CanGetById")]
     public Product GetProductById(int id)
     {
         var product = products.FirstOrDefault((p) => p.Id == id);
         if (product == null)
         {
             throw new HttpResponseException(HttpStatusCode.NotFound);
         }
         return product;
     }
}
[VB.NET]
<VGAuthorize(Roles:="Admin")> _
Public Class ProductionController
    Inherits ApiController
    Private products As Product() = New Product() {New Product() With { _
        .Id = 1, _
        .Name = "Tomato Soup", _
        .Category = "Groceries", _
        .Price = 1 _
    }, New Product() With { _
        .Id = 2, _
        .Name = "Yo-yo", _
        .Category = "Toys", _
        .Price = 3.75D _
    }, New Product() With { _
        .Id = 3, _
        .Name = "Hammer", _
        .Category = "Hardware", _
        .Price = 16.99D _
    }}

    <VGAuthorize(Permissions:="CanGetAllRoles", Roles:="RoleManager")> _
    Public Function GetAllProducts() As IEnumerable(Of Product)
        Return products
    End Function

    <VGAuthorize(Permissions:="ReadOnly")>
    <VGAuthorize(Permissions:="CanGetById")> _
    Public Function GetProductById(id As Integer) As Product
        Dim product = products.FirstOrDefault(Function(p) p.Id = id)
        If product Is Nothing Then
            Throw New HttpResponseException(HttpStatusCode.NotFound)
        End If
        Return product
    End Function 
End Class