Yellow! We’re going to create the tutorial where we implement
the webapi. Let’s start right now.
We will create a separate webapi, which can be hosted
anywhere without support of any MVC website. We will be using visual studio
2013 ultimate with update 4. Given below are the step by step instructions on
creating a webapi(solely a webapi).
- Then
you select Empty and check webapi (don’t or do host it in azure cloud.. your
choice. I won’t do it though)
- You can make any number of fields (properties, Also a model is mapped to a database table as it is so make sure you are creating fields and their attributes as you want them to be in database) you want in this model. For now we will add id and title etc., the good thing is you can add the data annotations. To use data annotations you need to use System.ComponentModel.DataAnnotations Using this you can assign attributes to declared fields.. We are using three fields right now. “ID, Title and Details”
- After you’re done adding a model.. You need to add controller for that model. Using that controller the external agents can communicate with our webapi. • Before creating a controller you should build the solution
- After building the solution, right click on controllers folder in solution explorer and “add controller”. Select “Web API 2 controller with actions, using Entity Framework” and press Add
In the next dialogue box select the model you need to add a controller for and add a newcontext class, if it’s not already there and then press Add
- Now our very first and the most basic webapi is ready. Remember we have not added any method for authorization to this api, neither we enabled cross origin requests(means only the localhost can access this webapi for now), but lets quickly check it and then we will move forward to cross origin requests, getting data from database, requesting data using ajax and authorization.
- To test web api in real time we will use “Telerik fiddler”. Lets test the get method without any input parameter
- First of all run the webapi which we have just created (for me it’s hosted at localhost:13954),
That
happened because we did not specified any controller for this web api. To route
the request to a controller we need to specify /api/controller name in our
request e.g., localhost:13954/api/mymodels
Here our controller’s name is mymodels. Let’s browse to it and see what happens.
We got a 200 page with nothing in it, because our model contains no data as of now. When we tried to get a page from our controller. The Getmymodels()function gets called, for a post request a postmymodels function will get called which will take “mymodel” in request body to update our model data. Lets try the post
This is what we posted to my models
Here our controller’s name is mymodels. Let’s browse to it and see what happens.
We got a 200 page with nothing in it, because our model contains no data as of now. When we tried to get a page from our controller. The Getmymodels()function gets called, for a post request a postmymodels function will get called which will take “mymodel” in request body to update our model data. Lets try the post
This is what we posted to my models
This is the result we
got from our server which is hosting the webapi. (201 means a new entry was created
in the webapi by localhost)
Since we posted
something there is something in our model now. Let try to get it and see what
we retrieve. Weee… now the request body returned with the entry we made with
our post request in previous step.
We
can create functions in our controller to take arguments. In this current
controller there is a function which takes “id” as an argument to return the
result specific to that “id”. For that we need to browse to localhost:13954/api/mymodels/1
This
brings us just the data for id 1. It’s quite easy to relate to database using
webapi. All we have to do is to make enough models and query the database on
user requests. Lets hope you have the basic understanding of webapi2. Next we
will go ahead and integrate it with a database and use ajax requests to carry
out CRUD operations
Resolveing error
Resolveing error
Run
the Enable-Migrations
-EnableAutomaticMigrations command
in Package Manager Console
Run
the Update-Database command in
Package manager Console
Adding
a model automatically creates that in database for you. So all you have to
focus on is creating models. Design a database and add it to models and use controller
to access information. Easy Cheesy
ENABLE THE AUTHORIZATION and TOKEN
GENERATION
We should make our webapi secure so that
anonymouse users cannot access it or we can just use user authentication to
make sure sensitive areas of our webapi are accessed only by authorized
clients. To use authorization check on a controller we just need to add the
[Authorize] Annotation on our controller
Lets start with adding authorization to our
webapi
- First
of all add a new class(Owin Startup class) to our webapi project.
- Once you’re done adding the startup class and the owin packages. Now you need to add a method to allocate tokens to users requests. For this we need to add a piece of code to our startup class
It basically creates a new authentication options object and hosts a smalls erver to entertain authentication requests from clients. You can select user name and password from a text file or database or in what ever form you want to .. Here I have just hardcoded the username and password for demo purposes. Also one never uses “http” for authorization requests.. it is absolutely insecure. So you must make sure that you’re using “https” whenever you deploy this on public networks
using System;using System.Threading.Tasks;using Microsoft.Owin;using Microsoft.Owin.Security.OAuth;using Owin;using System.Collections.Generic;using System.Linq;using System.Security.Claims;using System.Web;[assembly: OwinStartup(typeof(first.Startup))]namespace first{public class Startup{public void Configuration(IAppBuilder app){// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());app.UseOAuthAuthorizationServer(newOAuthAuthorizationServerOptions(){AllowInsecureHttp = true,TokenEndpointPath = new PathString("/token"),Provider = new OAuthAuthorizationServerProvider(){OnValidateClientAuthentication = async c =>{c.Validated();},OnGrantResourceOwnerCredentials = async c =>{if (c.UserName == "username" && c.Password == "password"){ClaimsIdentity id = new ClaimsIdentity(new Claim[] {new Claim(ClaimTypes.Name,c.UserName)},OAuthDefaults.AuthenticationType);c.Validated(id);}}}});}}} - Let us test our authorization We tried to access the webapi’s secure controller through browser without any authentication and webapi denied our request.Lets try to get a token from browser.. Lets goto fiddler . We need to get a token first.. Lets get a token
We get a token specifying the above shown properties. The result for above request is shown below
The webapi returned the token. We will have to use this token for every request we make from now onwards.. Lets make a get request using this token
We made a simple get request using this token. Now lets see the result for this request.
This is all for making a webapi. With authorization enabled.. Next we will discuss creating client application in webforms and making complicated requests. Also we will go into more detail regarding database.





















No comments:
Post a Comment