Thứ Hai, 4 tháng 4, 2016

Note Web-API

1.   AcceptVerbs
To allow multiple HTTP methods for an action, or to allow HTTP methods other than GET, PUT, POST, and DELETE, use the AcceptVerbs attribute, which takes a list of HTTP methods.
public class ProductsController : ApiController
{
    [AcceptVerbs("GET", "HEAD")]
    public Product FindProduct(id) { }
 
    // WebDAV method
    [AcceptVerbs("MKCOL")]
    public void MakeCollection() { }
}

2.   NonAction
To prevent a method from getting invoked as an action, use the NonAction attribute. This signals to the framework that the method is not an action, even if it would otherwise match the routing rules.
// Not an action method.
[NonAction]  
public string GetPrivateData() { ... }


3.   Default in route URI
routes.MapHttpRoute(
    name: "Root",
    routeTemplate: "api/root/{id}",
    defaults: new { controller = "customers", id = RouteParameter.Optional }
);
If the URI path is "api/root/8", the dictionary will contain two values:
·         controller: "customers"
·         id: "8"

4.   HTTP Methods
HTTP Methods. The framework only chooses actions that match the HTTP method of the request, determined as follows:
1.       You can specify the HTTP method with an attribute: AcceptVerbsHttpDeleteHttpGetHttpHeadHttpOptionsHttpPatch,HttpPost, or HttpPut.
2.       Otherwise, if the name of the controller method starts with "Get", "Post", "Put", "Delete", "Head", "Options", or "Patch", then by convention the action supports that HTTP method.
3.       If none of the above, the method supports POST.

5.   RoutePrefix
Use a tilde (~) on the method attribute to override the route prefix:
[RoutePrefix("api/books")]
public class BooksController : ApiController
{
    // GET /api/authors/1/books
    [Route("~/api/authors/{authorId:int}/books")]
    public IEnumerable<Book> GetByAuthor(int authorId) { ... }
 
    // ...
}

6.   Route Constraints
Route constraints let you restrict how the parameters in the route template are matched. The general syntax is "{parameter:constraint}". For example:
[Route("users/{id:int}"]
public User GetUserById(int id) { ... }

[Route("users/{name}"]
public User GetUserByName(string name) { ... }
Here, the first route will only be selected if the "id" segment of the URI is an integer. Otherwise, the second route will be chosen.
The following table lists the constraints that are supported.
Constraint
Description
Example
alpha
Matches uppercase or lowercase Latin alphabet characters (a-z, A-Z)
{x:alpha}
bool
Matches a Boolean value.
{x:bool}
datetime
Matches a DateTime value.
{x:datetime}
decimal
Matches a decimal value.
{x:decimal}
double
Matches a 64-bit floating-point value.
{x:double}
float
Matches a 32-bit floating-point value.
{x:float}
guid
Matches a GUID value.
{x:guid}
int
Matches a 32-bit integer value.
{x:int}
length
Matches a string with the specified length or within a specified range of lengths.
{x:length(6)}
{x:length(1,20)}
long
Matches a 64-bit integer value.
{x:long}
max
Matches an integer with a maximum value.
{x:max(10)}
maxlength
Matches a string with a maximum length.
{x:maxlength(10)}
min
Matches an integer with a minimum value.
{x:min(10)}
minlength
Matches a string with a minimum length.
{x:minlength(10)}
range
Matches an integer within a range of values.
{x:range(10,50)}
regex
Matches a regular expression.
{x:regex(^\d{3}-\d{3}-\d{4}$)}
Notice that some of the constraints, such as "min", take arguments in parentheses. You can apply multiple constraints to a parameter, separated by a colon.
[Route("users/{id:int:min(1)}")]
public User GetUserById(int id) { ... }

7.   Update Model Object - db.Entry
// Update Author
public async Task<IHttpActionResult> PutAuthor(int id, Author author)
{
     ......

     db.Entry(author).State = EntityState.Modified;
     try
     {
           await db.SaveChangesAsync();
     }
     catch (DbUpdateConcurrencyException)
     {
           if (!AuthorExists(id))
           {
                return NotFound();
           }
           else
           {
                throw;
           }
     }

     return StatusCode(HttpStatusCode.NoContent);
}


8.   Eager , Lazy, Explicit Loading
http://www.asp.net/web-api/overview/data/using-web-api-with-entity-framework/part-4


9.   Error Auth google
Install the Nuget Package which contains the Google OAuth provider.
Install-Package Microsoft.Owin.Security.Google
app.UseGoogleAuthentication(
         clientId: "000000000000000.apps.googleusercontent.com",
         clientSecret: "000000000000000");

http://www.oauthforaspnet.com/providers/google/