1)What is WebAPI? (or) Explain about WebAPI
ASP.NET Web API is a framework defined by microsoft, this makes us to build HTTP services very easily
By using HTTP services we can reach more no of cutomers , different types of browsers and diffrent devices
Web API is open source for building REST-ful services
2)Explain routing in WebAPI (or) WebAPI routing ?
Like ASP.NET MVC ,IN ASP.NET Web API also controller is a class that handles HTTP requests.
When the Web API framework receives a request, its find the appropriate controller and action method to perform an action.
To determine which action to invoke, the framework uses a routing table,Which is in WebApiConfig.cs file placed in the App_Start folder in project.
routes.MapHttpRoute(
name: "API Default",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
From above "api" is a literal path segment, and {controller} and {id} are placeholder variables.
3) What is the difference between MVC Routing and Web API Routing?
WebAPI routing structure in WebApiConfig.cs:
routes.MapHttpRoute(
name: "API Default",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
MVC routing structure in RouteConfig.cs:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
In WebAPI route "api" string literal is prefixed for route.
In WebAPI route {action} place holder is optional
4) How parameter binding works in Web API?
Below are the rules followed by WebAPI before binding parameters –
1)If it is simple parameters like – bool,int, double etc. then value will be obtained from the URL.
2)Value read from message body in case of complex types.
5)Action Results in WebAPI ?
void : Nothing return
HttpResponseMessage : Convert directly to HTTp Response message
IHttpActionResult : Call ExecuteAsync to create an HttpResponseMessage, then convert to an HTTP response message.
Some other type : Write a serialized return value
HttpResponseMessage Example :
public HttpResponseMessage GetData()
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, "value");
response.Content = new StringContent("hello", Encoding.Unicode);
response.Headers.CacheControl = new CacheControlHeaderValue()
{
MaxAge = TimeSpan.FromMinutes(20)
};
return response;
}
public HttpResponseMessage GetData()
{
// Get a list of Students from a database.
IEnumerable<Student> students = GetStudentsFromDB();
// Write the list to the response body.
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, students);
return response;
}
IHttpActionResult:
It defines an HttpResponseMessage
Simplifies unit testing your controllers.
Moves common logic for creating HTTP responses into separate classes.
Makes the intent of the controller action clearer, by hiding the low-level details of constructing the response.
public class MyResult : IHttpActionResult
{
string _value;
HttpRequestMessage _request;
public MyResult(string value, HttpRequestMessage request)
{
_value = value;
_request = request;
}
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
var response = new HttpResponseMessage()
{
Content = new StringContent(_value),
RequestMessage = _request
};
return Task.FromResult(response);
}
}
public class ValuesController : ApiController
{
public IHttpActionResult Get()
{
return new MyResult("Pass", Request);
}
}
6)Routing table syntax in WebAPI ?
routes.MapHttpRoute(
name: "API Default",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
If no route matches, the client receives a 404 error.
Instead of using Naming conventions on action method , use HTTP action methods like HttpGet, HttpPut, HttpPost, or HttpDelete attribute.
To allow multiple HTTP methods for one action use the AcceptVerbs attribute, which takes a list of HTTP methods.
7)How to ignore the actions WebAPI?
[NonAction] attribute ,we can ignore the actions.
8)How parmeters gets the value in WebAPI ?
Using the following way parameters get the values
1) URI
2) Request body
3) Custom Binding
9)How to enable Attribute routing ?
TO enable attribute routing, call MapHttpAttributeRoutes(); method in WebApi config file.
public static void Register(HttpConfiguration config)
{
// Web API routes
config.MapHttpAttributeRoutes();
// Other Web API configuration not shown.
}
10)Can we apply constraints at route level ?
Yes we can apply.
[Route("students/{id:int}"]
public User GetStudentById(int id) { ... }
[Route("students/{name}"]
public User GetStudentByName(string name) { ... }
From above Here, the first route will only be selected whenever the "id" segment of the URI is an integer. Otherwise, the second route will be chosen.
11)How to mention Roles and users using Authorize attribute in Web API?
// Restrict by Name
[Authorize(Users="Shiva,Jai")]
public class StudentController : ApiController
{
}
// Restrict by Role
[Authorize(Roles="Administrators")]
public class StudnetController : ApiController
{
}
12)How to enable SSL to ASP.NET web?
To enable SSL to ASP.NET web , click project properties there you can see this option.
13)How to add certificates to website?
go to run type command mmc click on ok then its opend certificate add window
14)Write a LINQ code for authenticate the user?
public static bool Login(string UN, string pwd)
{
StudentDBEntities students = new StudentDBEntities()
students.sudent.Any(e => e.UserName.Equals(UN) && e=>e.Password.Equlas(UN)) // students has morethan one table
}
15)How to navigate other page in JQuery?
using widow.location.href = "~/homw.html";
16)Exception handling in WebAPI?
The HttpResponseException most common exception in WebAPI.
public Product GetStudentDetails(int rno)
{
Student studentinfo = repository.Get(rno);
if (studentinfo == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return studentinfo;
}
using exception filters we can handle the exceptions at action method level or controller level
if you want to apply any filter to entire application , register the filter in WebAPI confil file
using Exception hadlers and Exception loogers aslo can handle the Exceptions
17) What is NonActionAttribute class in WebAPI?
If we want to restrict the particular actionmethod accessing from browser, we can NonAction attribute.public ActionResult
[NonAction]
public ActionResult Insert(){
return View();
}
Above method not getting access from browser
18) How parameter binding works in Web API?
Below are the rules followed by WebAPI before binding parameters –
1)If it is simple parameters like – bool,int, double etc. then value will be obtained from the URL.
2)Value read from message body in case of complex types.
19)What is the difference between SOAP and REST?
SOAP
----
SOAP is a protocal , communication should be done in the form of XML
SOAP based reads cannot be cached
Slower than rest
REST
----
Rest is architectual pattren , supports many data pattrens
Rest reads can be cached
Fater than SOAP
20)Which top 5 New Features have been included in ASP.NET Web API 2?
1.Attribute Routing,
2.Web API OData
3.CORS ? Cross Origin Resource Sharing,
4.IHttpActionResult
5.OWIN (Open Web Interface for .NET) self hosting,
21)What are different status codes available in web?
1**: Informational-It means the request has been received and the process is continuing.
2**: Success
3**: Redirection-It means further action must be taken in order to complete the request.
4**: ClientError-It means the request contains incorrect syntax or cannot be fulfilled
5**: ServerError
22)Use of AllowAnonymousAttribute Class in WebAPI?
Use of we can skip the Authentication and authorizaion for a action method. It is not asking credintial while accessing a action method
Authorize]
public class StudentController : Controller {
[AllowAnonymous]
public ActionResult Login()
{
// ...
}
[AllowAnonymous]
public ActionResult Register()
{
// ...
}
23)Use of FromUri attribute in web api ? (and) Use of FromBody attribute in web api?
Bydefault in WebAPI reads the simple parameters like int,bool,long, string,date..etc... form URI
Bydefault in WebAPI reads the Complex parameters like objects form body
Above is the default behaviour , if want to override default then you can use FromBody,FromUri attributes
FromUri attribute that specifies that an action parameter comes from the URI of incoming request
public HttpResponseMessage Post([FromUri] int id)
{
}
FromBody attribute that specifies that an action parameter comes only from the entity body of the incoming request
public HttpResponseMessage Post([FromBody]int id)
{
}
24)What is the use of HttpBindNever attribute Class in webapi example?
public class Student
{
[HttpBindNever]
Public int studentno{get;set;}
[Required]
Public string studentName {get;set;}
}
HttpBindNever attribute, which prevents Web API from assigning a value to a property from the request.
This ensures I don’t get unexpected or undesired behavior by accepting request values for properties that I need to set in the application.
In the above example i dont want to set stdentno property, So that i am using HttpBindNever attribute.
ASP.NET Web API is a framework defined by microsoft, this makes us to build HTTP services very easily
By using HTTP services we can reach more no of cutomers , different types of browsers and diffrent devices
Web API is open source for building REST-ful services
2)Explain routing in WebAPI (or) WebAPI routing ?
Like ASP.NET MVC ,IN ASP.NET Web API also controller is a class that handles HTTP requests.
When the Web API framework receives a request, its find the appropriate controller and action method to perform an action.
To determine which action to invoke, the framework uses a routing table,Which is in WebApiConfig.cs file placed in the App_Start folder in project.
routes.MapHttpRoute(
name: "API Default",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
From above "api" is a literal path segment, and {controller} and {id} are placeholder variables.
3) What is the difference between MVC Routing and Web API Routing?
WebAPI routing structure in WebApiConfig.cs:
routes.MapHttpRoute(
name: "API Default",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
MVC routing structure in RouteConfig.cs:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
In WebAPI route "api" string literal is prefixed for route.
In WebAPI route {action} place holder is optional
4) How parameter binding works in Web API?
Below are the rules followed by WebAPI before binding parameters –
1)If it is simple parameters like – bool,int, double etc. then value will be obtained from the URL.
2)Value read from message body in case of complex types.
5)Action Results in WebAPI ?
void : Nothing return
HttpResponseMessage : Convert directly to HTTp Response message
IHttpActionResult : Call ExecuteAsync to create an HttpResponseMessage, then convert to an HTTP response message.
Some other type : Write a serialized return value
HttpResponseMessage Example :
public HttpResponseMessage GetData()
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, "value");
response.Content = new StringContent("hello", Encoding.Unicode);
response.Headers.CacheControl = new CacheControlHeaderValue()
{
MaxAge = TimeSpan.FromMinutes(20)
};
return response;
}
public HttpResponseMessage GetData()
{
// Get a list of Students from a database.
IEnumerable<Student> students = GetStudentsFromDB();
// Write the list to the response body.
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, students);
return response;
}
IHttpActionResult:
It defines an HttpResponseMessage
Simplifies unit testing your controllers.
Moves common logic for creating HTTP responses into separate classes.
Makes the intent of the controller action clearer, by hiding the low-level details of constructing the response.
public class MyResult : IHttpActionResult
{
string _value;
HttpRequestMessage _request;
public MyResult(string value, HttpRequestMessage request)
{
_value = value;
_request = request;
}
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
var response = new HttpResponseMessage()
{
Content = new StringContent(_value),
RequestMessage = _request
};
return Task.FromResult(response);
}
}
public class ValuesController : ApiController
{
public IHttpActionResult Get()
{
return new MyResult("Pass", Request);
}
}
6)Routing table syntax in WebAPI ?
routes.MapHttpRoute(
name: "API Default",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
If no route matches, the client receives a 404 error.
Instead of using Naming conventions on action method , use HTTP action methods like HttpGet, HttpPut, HttpPost, or HttpDelete attribute.
To allow multiple HTTP methods for one action use the AcceptVerbs attribute, which takes a list of HTTP methods.
7)How to ignore the actions WebAPI?
[NonAction] attribute ,we can ignore the actions.
8)How parmeters gets the value in WebAPI ?
Using the following way parameters get the values
1) URI
2) Request body
3) Custom Binding
9)How to enable Attribute routing ?
TO enable attribute routing, call MapHttpAttributeRoutes(); method in WebApi config file.
public static void Register(HttpConfiguration config)
{
// Web API routes
config.MapHttpAttributeRoutes();
// Other Web API configuration not shown.
}
10)Can we apply constraints at route level ?
Yes we can apply.
[Route("students/{id:int}"]
public User GetStudentById(int id) { ... }
[Route("students/{name}"]
public User GetStudentByName(string name) { ... }
From above Here, the first route will only be selected whenever the "id" segment of the URI is an integer. Otherwise, the second route will be chosen.
11)How to mention Roles and users using Authorize attribute in Web API?
// Restrict by Name
[Authorize(Users="Shiva,Jai")]
public class StudentController : ApiController
{
}
// Restrict by Role
[Authorize(Roles="Administrators")]
public class StudnetController : ApiController
{
}
12)How to enable SSL to ASP.NET web?
To enable SSL to ASP.NET web , click project properties there you can see this option.
13)How to add certificates to website?
go to run type command mmc click on ok then its opend certificate add window
14)Write a LINQ code for authenticate the user?
public static bool Login(string UN, string pwd)
{
StudentDBEntities students = new StudentDBEntities()
students.sudent.Any(e => e.UserName.Equals(UN) && e=>e.Password.Equlas(UN)) // students has morethan one table
}
15)How to navigate other page in JQuery?
using widow.location.href = "~/homw.html";
16)Exception handling in WebAPI?
The HttpResponseException most common exception in WebAPI.
public Product GetStudentDetails(int rno)
{
Student studentinfo = repository.Get(rno);
if (studentinfo == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return studentinfo;
}
using exception filters we can handle the exceptions at action method level or controller level
if you want to apply any filter to entire application , register the filter in WebAPI confil file
using Exception hadlers and Exception loogers aslo can handle the Exceptions
17) What is NonActionAttribute class in WebAPI?
If we want to restrict the particular actionmethod accessing from browser, we can NonAction attribute.public ActionResult
[NonAction]
public ActionResult Insert(){
return View();
}
Above method not getting access from browser
18) How parameter binding works in Web API?
Below are the rules followed by WebAPI before binding parameters –
1)If it is simple parameters like – bool,int, double etc. then value will be obtained from the URL.
2)Value read from message body in case of complex types.
19)What is the difference between SOAP and REST?
SOAP
----
SOAP is a protocal , communication should be done in the form of XML
SOAP based reads cannot be cached
Slower than rest
REST
----
Rest is architectual pattren , supports many data pattrens
Rest reads can be cached
Fater than SOAP
20)Which top 5 New Features have been included in ASP.NET Web API 2?
1.Attribute Routing,
2.Web API OData
3.CORS ? Cross Origin Resource Sharing,
4.IHttpActionResult
5.OWIN (Open Web Interface for .NET) self hosting,
21)What are different status codes available in web?
1**: Informational-It means the request has been received and the process is continuing.
2**: Success
3**: Redirection-It means further action must be taken in order to complete the request.
4**: ClientError-It means the request contains incorrect syntax or cannot be fulfilled
5**: ServerError
22)Use of AllowAnonymousAttribute Class in WebAPI?
Use of we can skip the Authentication and authorizaion for a action method. It is not asking credintial while accessing a action method
Authorize]
public class StudentController : Controller {
[AllowAnonymous]
public ActionResult Login()
{
// ...
}
[AllowAnonymous]
public ActionResult Register()
{
// ...
}
23)Use of FromUri attribute in web api ? (and) Use of FromBody attribute in web api?
Bydefault in WebAPI reads the simple parameters like int,bool,long, string,date..etc... form URI
Bydefault in WebAPI reads the Complex parameters like objects form body
Above is the default behaviour , if want to override default then you can use FromBody,FromUri attributes
FromUri attribute that specifies that an action parameter comes from the URI of incoming request
public HttpResponseMessage Post([FromUri] int id)
{
}
FromBody attribute that specifies that an action parameter comes only from the entity body of the incoming request
public HttpResponseMessage Post([FromBody]int id)
{
}
24)What is the use of HttpBindNever attribute Class in webapi example?
public class Student
{
[HttpBindNever]
Public int studentno{get;set;}
[Required]
Public string studentName {get;set;}
}
HttpBindNever attribute, which prevents Web API from assigning a value to a property from the request.
This ensures I don’t get unexpected or undesired behavior by accepting request values for properties that I need to set in the application.
In the above example i dont want to set stdentno property, So that i am using HttpBindNever attribute.
25)Use of HttpError Class in WebAPI?
It is a container for storing error information. This information is stored as key/value pairs.
public HttpResponseMessage GetStudentDetails(int rno)
{
Student studentinfo = Collegerepository.Get(id);
if (item == null)
{
var message = string.Format("Student with Roll Number = {0} not found", rno);
HttpError err = new HttpError(message);
return Request.CreateResponse(HttpStatusCode.NotFound, err);
}
else
{
return Request.CreateResponse(HttpStatusCode.OK, studentinfo);
}
}
It is a container for storing error information. This information is stored as key/value pairs.
public HttpResponseMessage GetStudentDetails(int rno)
{
Student studentinfo = Collegerepository.Get(id);
if (item == null)
{
var message = string.Format("Student with Roll Number = {0} not found", rno);
HttpError err = new HttpError(message);
return Request.CreateResponse(HttpStatusCode.NotFound, err);
}
else
{
return Request.CreateResponse(HttpStatusCode.OK, studentinfo);
}
}
For Part2 click here
Thanks for visiting this blog. How is the content?. Your comment is great gift to my work. Cheers.
Thanks for providing your information, for more updates on Azure get touch with Azure Online Training
ReplyDeleteI am glad that I saw this post. It is informative blog for us and we need this type of blog thanks for share this blog, Keep posting such instructional blogs and I am looking forward for your future posts. Python Projects for Students Data analytics is the study of dissecting crude data so as to make decisions about that data. Data analytics advances and procedures are generally utilized in business ventures to empower associations to settle on progressively Python Training in Chennai educated business choices. In the present worldwide commercial center, it isn't sufficient to assemble data and do the math; you should realize how to apply that data to genuine situations such that will affect conduct. In the program you will initially gain proficiency with the specialized skills, including R and Python dialects most usually utilized in data analytics programming and usage; Python Training in Chennai at that point center around the commonsense application, in view of genuine business issues in a scope of industry segments, for example, wellbeing, promoting and account. Project Center in Chennai
Deletegood
ReplyDeleteThanks
ReplyDeleteHi,
ReplyDeleteHope you are doing good, I noticed your website in Google and found useful.
I own a tech blog that might be interesting.
Feel free to check (https://www.sharepointcafe.net/) and if it is worth for you please feel free to link to it.
Cheers,
SharePointCafe Team