26)Use of HttpHeadAttribute class in WebAPI?
This is identical to a GET request, but only returns the headers for the response, not the response body.
Theoretically faster, commonly used for checking to see if a particular resources exists or can be accessed.
27)Use of AcceptVerbs Attribute in WebAPI?
If you want to one ActionMethod support more than one HTTP method you can use AcceptVerbs attribute.
[AcceptVerbs("POST", "PUT")]
public IHttpActionResult Add(string title)
{
return Ok();
}
28)Use of HttpPatch Attribute in WebAPI ?
whenever we use HttpPut attribute , we should send complete model data to an action method, Even we have single property update, this is not always good if we have large data, To avoid this situation we use HttpPatch attribute.
using HttpPatch attribute, we can support partial mode updates.It reduces complexity in case of bigger tables
[HttpPatch]
public void UpdateStudentLastName(int rno,[FromBody] string lastName)
{
var student=lstStudent.FirstOrDefault(e => e.Rno == rno);
student.LastName = lastName;
lstStdent.SaveChanges();
}
29)How can we avoid circular reference in the relationship issue in WebAPI?
Ex:Many to Many Relationship
Let’s say we have a StudentInfo entity and a SubjectInfo entity. One Student can be enrolled in many Subjects and One Subject can have many Students
public class StudentInfo
{
public StudentInfo()
{
Subjects = new HashSet<Subject>();
}
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public ICollection<SubjectInfo> Subjects { get; set; }
}
public class Subject
{
public Subject()
{
StudentInfos = new HashSet<StudentInfo>();
}
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<StudentInfo> Students { get; set; }
}
There is a circular reference in the relationship between Subject and StudentInfo class.
This is a problem for the standard serialization process, which will report an error when it finds such a loop to avoid circular reference , we need to following in WebAPI config file.
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
--------------------------------
---------------------------------
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
}
}
Let’s say we have a StudentInfo entity and a SubjectInfo entity. One Student can be enrolled in many Subjects and One Subject can have many Students
public class StudentInfo
{
public StudentInfo()
{
Subjects = new HashSet<Subject>();
}
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public ICollection<SubjectInfo> Subjects { get; set; }
}
public class Subject
{
public Subject()
{
StudentInfos = new HashSet<StudentInfo>();
}
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<StudentInfo> Students { get; set; }
}
There is a circular reference in the relationship between Subject and StudentInfo class.
This is a problem for the standard serialization process, which will report an error when it finds such a loop to avoid circular reference , we need to following in WebAPI config file.
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
--------------------------------
---------------------------------
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
}
}
30)What is the DataBase intializer classes in WebAPI?
DropCreateDatabaseAlways<T> The database is dropped and re-created every time the database
context is initialized.
DropCreateDatabaseIfModelChanges<T> The database is dropped and re-created when any of the model classes
are changed.
CreateDatabaseIfNotExists<T> The database is created only if it does not already exist.
Commonly Used MVC Framework Classes and Their Web API Counterparts
____________________________________________________________________
MVC Class or Interface Web API Equivalent
______________________ ___________________________________________
System.Web.Mvc.IController System.Web.Http.Controllers.IHttpController
System.Web.Mvc.Controller System.Web.Http.ApiController
System.Web.HttpContext System.Web.Http.Controllers.HttpRequestContext
System.Web.HttpRequest System.Net.Http.HttpRequestMessage
System.Web.HttpResponse System.Net.Http.HttpResponseMessage
System.Web.HttpApplication System.Web.Http.HttpConfiguration
31)What is namespace for WebAPI , When it was introduced ?
System.Net.Http namespace, which was introduced in .NET 4.5
32)How to locate TCP port in WebAPI ?
select the solution and go to Properties from the Visual Studio go to Project menu, select the Web tab, and locate the Project URL field,
or
Look at the browser bar, which shows the URL that Visual Studio told the browser to request.
33)What is the very crucial class in WebAPI ?
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional });
}
}
The Properties Defined by the HttpConfiguration Class
Name :Description
_________________ _____________
DependencyResolver : Gets or sets the class used for dependency injection.
Filters : Gets or sets the request filters
Formatters : Gets or sets the media type formatters
IncludeErrorDetailPolicy :Gets or sets whether details are included in error messages
MessageHandlers : Gets or sets the message handlers
ParameterBindingRules : Gets the rules by which parameters are bound Properties Returns a ConcurrentDictionary<object, object> that can be used as a general
property bag to coordinate the behavior of components.
Routes : Gets the set of routes configured for the application.
Services : Returns the Web API services.
34)What is Dependency Injection ?
Dependency injection (DI) breaks the direct dependency between classes
A DI container is configured with mappings between interfaces and implementation classes
DI allows interfaces to be used without direct knowledge of the classes that implement them, creating loosely coupled components
interface IproductInfo
{
void getProduct();
void putProduct();
}
public class Product : IproductInfo
{
public void getProduct()
{
Console.WriteLine("Am from get products");
}
public void putProduct()
{
Console.WriteLine("Am from put products");
}
}
class Test
{
IproductInfo ipr;
public Test(IproductInfo p)
{
ipr = p;
}
public void getDetails()
{
ipr.getProduct();
}
public void putDetails()
{
ipr.putProduct();
}
static void Main(string[] args)
{
IproductInfo p = new Product();
Test Tbj = new Test(p);
Tbj.getDetails();
Tbj.putDetails();
Console.ReadLine();
}
}
DropCreateDatabaseAlways<T> The database is dropped and re-created every time the database
context is initialized.
DropCreateDatabaseIfModelChanges<T> The database is dropped and re-created when any of the model classes
are changed.
CreateDatabaseIfNotExists<T> The database is created only if it does not already exist.
Commonly Used MVC Framework Classes and Their Web API Counterparts
____________________________________________________________________
MVC Class or Interface Web API Equivalent
______________________ ___________________________________________
System.Web.Mvc.IController System.Web.Http.Controllers.IHttpController
System.Web.Mvc.Controller System.Web.Http.ApiController
System.Web.HttpContext System.Web.Http.Controllers.HttpRequestContext
System.Web.HttpRequest System.Net.Http.HttpRequestMessage
System.Web.HttpResponse System.Net.Http.HttpResponseMessage
System.Web.HttpApplication System.Web.Http.HttpConfiguration
31)What is namespace for WebAPI , When it was introduced ?
System.Net.Http namespace, which was introduced in .NET 4.5
32)How to locate TCP port in WebAPI ?
select the solution and go to Properties from the Visual Studio go to Project menu, select the Web tab, and locate the Project URL field,
or
Look at the browser bar, which shows the URL that Visual Studio told the browser to request.
33)What is the very crucial class in WebAPI ?
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional });
}
}
The Properties Defined by the HttpConfiguration Class
Name :Description
_________________ _____________
DependencyResolver : Gets or sets the class used for dependency injection.
Filters : Gets or sets the request filters
Formatters : Gets or sets the media type formatters
IncludeErrorDetailPolicy :Gets or sets whether details are included in error messages
MessageHandlers : Gets or sets the message handlers
ParameterBindingRules : Gets the rules by which parameters are bound Properties Returns a ConcurrentDictionary<object, object> that can be used as a general
property bag to coordinate the behavior of components.
Routes : Gets the set of routes configured for the application.
Services : Returns the Web API services.
34)What is Dependency Injection ?
Dependency injection (DI) breaks the direct dependency between classes
A DI container is configured with mappings between interfaces and implementation classes
DI allows interfaces to be used without direct knowledge of the classes that implement them, creating loosely coupled components
interface IproductInfo
{
void getProduct();
void putProduct();
}
public class Product : IproductInfo
{
public void getProduct()
{
Console.WriteLine("Am from get products");
}
public void putProduct()
{
Console.WriteLine("Am from put products");
}
}
class Test
{
IproductInfo ipr;
public Test(IproductInfo p)
{
ipr = p;
}
public void getDetails()
{
ipr.getProduct();
}
public void putDetails()
{
ipr.putProduct();
}
static void Main(string[] args)
{
IproductInfo p = new Product();
Test Tbj = new Test(p);
Tbj.getDetails();
Tbj.putDetails();
Console.ReadLine();
}
}
35)What is the namespace for HttpRequestMessage , HttpResponseMessage classes in WebAPI?
HTTP requests and responses that is defined in System.Net.Http.
36)What is the use of ApiController class in WebAPI?
which is the standard base class for creating Web API controllers and provides support for features such as action methods, model binding, and validation and error handling.
37)How to remove XML formatter from in WebAPI?.
go to WebApiConfig.cs file , In register method we need to write following
config.Formatters.Remove(config.Formatters.XmlFormatter)
38)What is content negotiation in WebAPI?
Web API selects the right format for each client this is called as content negotiation.
39)What is the Namespace which contain HTTP status codes info?
System.Net.HttpStatusCode
40)What is base class for Action Result type in C#?
Web API action methods implement the IHttpActionResult interface.
public IHttpActionResult GetStudent(int rno)
{
Product result = Repository.Products.Where(p => p.rno == rno).FirstOrDefault();
return result == null
? (IHttpActionResult) BadRequest("No Product Found") : Ok(result);
}
41) WebAPI status codes and its action results ?
200 -> Operation successful-> Ok(), Ok(data)
302->Temporary redirection -> Redirect(target),RedirectToRoute(name, props)
400 -> Bad request->BadRequest(),BadRequest(message),BadRequest(model)
404 ->Not found -> NotFound()
409 ->Conflict -> Conflict()
(This status code is used when the request contravenes the internal rules defined by the web service)
200 -> Operation successful-> Ok(), Ok(data)
302->Temporary redirection -> Redirect(target),RedirectToRoute(name, props)
400 -> Bad request->BadRequest(),BadRequest(message),BadRequest(model)
404 ->Not found -> NotFound()
409 ->Conflict -> Conflict()
(This status code is used when the request contravenes the internal rules defined by the web service)
415-unsupported media type.
500 -> Internal server error -> InternalServerError(),InternalServerError(exception)
For all status codes IHttpActionResult is the base class.
42)What is content negotiation in WEBAPI?
Selecting the best representation for a given response when there are multiple representations available
43) What is media formatters in WEBAPI?
Media type formatter is a class which writes a CLR object to the body of the HTTP response , which reads a CLR object from the body of the HTTP request
44)What is thedifference between Accept header and Content-Type Header ?
Accept and Content-type are both headers sent from a client(browser say) to a service.
Accept header is a way for a client to specify the media type of the response content it is expecting
An example of an Accept header for a json request in REST ful
Accept: application/json
Content-type is a way to specify the media type of request being sent from the client to the server.
An example of Content-Type for a json request in REST ful
Content-Type: application/json
A json is being sent from a browser to a server, then the content type header would look like this
500 -> Internal server error -> InternalServerError(),InternalServerError(exception)
For all status codes IHttpActionResult is the base class.
42)What is content negotiation in WEBAPI?
Selecting the best representation for a given response when there are multiple representations available
43) What is media formatters in WEBAPI?
Media type formatter is a class which writes a CLR object to the body of the HTTP response , which reads a CLR object from the body of the HTTP request
44)What is thedifference between Accept header and Content-Type Header ?
Accept and Content-type are both headers sent from a client(browser say) to a service.
Accept header is a way for a client to specify the media type of the response content it is expecting
An example of an Accept header for a json request in REST ful
Accept: application/json
Content-type is a way to specify the media type of request being sent from the client to the server.
An example of Content-Type for a json request in REST ful
Content-Type: application/json
A json is being sent from a browser to a server, then the content type header would look like this
45)What is an API?
API- Application Programming Interface.
It is a software intermediary that allows two applications to talk each other.
46)What needs to do for support paging and filtering in WebAPI?
46)What needs to do for support paging and filtering in WebAPI?
WebAPI controller action method should return IQueryable result.
Public IQueryble<student> Get()
{
Return result.AsQueryable();
}
47) What are the challenges with API?
Injection attacks
CSS attacks
Sensitive data exposures
Poor security configuration
Poor logging mechanism
Problem with serialization and deserialization
For Part1 click here
No comments:
Post a Comment