1.1.1. Explain what is REST and RESTFUL?

REST represents REpresentational State Transfer; it is relatively new aspect of writing web api. RESTFUL is referred for web services written by applying REST architectural concept are called RESTful services, it focuses on system resources and how state of resource should be transported over HTTP protocol to a different clients written in different language. In RESTFUL web service http methods like GET, POST, PUT and DELETE can be used to perform CRUD operations.

1.1.2. Explain the architectural style for creating web api?

  • HTTP for client server communication
  • XML/JSON as formatting language: Simple URI as the address for the services
  • Stateless communication

1.1.3. what tools are required to test your web api?

Chrome postman, SOAPUI tool for SOAP WS and Firefox "poster" plugin for RESTFUL services.

1.1.4. what are the HTTP methods supported by REST?

  • GET: It requests a resource at the request URL. It should not contain a request body as it will be discarded. May be it can be cached locally or on the server.
  • POST: It submits information to the service for processing; it should typically return the modified or new resource
  • PUT: At the request URL it update the resource
  • DELETE: At the request URL it removes the resource
  • OPTIONS: It indicates which techniques are supported
  • HEAD: About the request URL it returns meta information

1.1.5. Mention what is the difference between SOAP and REST?

  • SOAP is a protocol through which two computer communicates by sharing XML document
  • SOAP permits only XML
  • SOAP based reads cannot be cached
  • SOAP is like custom desktop application, closely connected to the server
  • SOAP is slower than REST
  • It runs on HTTP but envelopes the message

  • Rest is a service architecture and design for network*based software architectures
  • REST supports many different data formats
  • REST reads can be cached
  • A REST client is more like a browser; it knows how to standardized methods and an application has to fit inside it REST is faster than SOAP
  • It uses the HTTP headers to hold meta information

1.1.6. Explain Web API Routing?

Routing is the mechanism of pattern matching as we have in MVC. These routes will get registered in Route Tables. Below is the sample route in Web API –

Routes.MapHttpRoute(
    Name: "MyFirstWebAPIRoute",
    routeTemplate: "api/{controller}/{id}
    defaults: new { id = RouteParameter.Optional}
};

1.1.7. List out the differences between WCF and Web API?

WCF

  • It is framework build for building or developing service oriented applications.
  • WCF can be consumed by clients which can understand XML.
  • WCF supports protocols like – HTTP, TCP, Named Pipes etc.

Web API

  • It is a framework which helps us to build/develop HTTP services
  • Web API is an open source platform.
  • It supports most of the MVC features which keep Web API over WCF.

1.1.8. What are the advantages of using REST in Web API?

REST always used to make less data transfers between client and server which makes REST an ideal for using it in mobile apps. Web API supports HTTP protocol thereby it reintroduces the old way of HTTP verbs for communication.

1.1.9. Difference between WCF Rest and Web API?

WCF Rest

  • "WebHttpBinding" to be enabled for WCF Rest.
  • For each method there has to be attributes like – "WebGet" and "WebInvoke"
  • For GET and POST verbs respectively.

Web API

  • Unlike WCF Rest we can use full features of HTTP in Web API.
  • Web API can be hosted in IIS or in application.

1.1.10. List out differences between MVC and Web API?

MVC

  • MVC is used to create a web app, in which we can build web pages.
  • For JSON it will return JSONResult from action method.
  • All requests are mapped to the respective action methods.

Web API

  • This is used to create a service using HTTP verbs.
  • This returns XML or JSON to client.
  • All requests are mapped to actions using HTTP verbs.

1.1.11. What are the advantages of Web API?

  • OData
  • Filters
  • Content Negotiation
  • Self Hosting
  • Routing
  • Model Bindings

1.1.12. Can we return view from Web API?

No. We cannot return view from Web API.

1.1.13. How we can restrict access to methods with specific HTTP verbs in Web API?

Attribute programming is used for this functionality. Web API will support to restrict access of calling methods with specific HTTP verbs. We can define HTTP verbs as attribute over method as shown below

[HttpPost]
public void UpdateTestCustomer(Customer c)
{
    TestCustomerRepository.AddCustomer(c);
}

1.1.14. Explain how to give alias name for action methods in Web API?

Using attribute "ActionName" we can give alias name for Web API actions. Eg:

[HttpPost]
[ActionName("AliasTestAction")]
public void UpdateTestCustomer(Customer c)
{
    TestCustomerRepository.AddCustomer(c);
}

1.1.15. What is the difference between MVC Routing and Web API Routing?

There should be at least one route defined for MVC and Web API to run MVC and Web API application respectively. In Web API pattern we can find "api/" at the beginning which makes it distinct from MVC routing. In Web API routing "action" parameter is not mandatory but it can be a part of routing.

1.1.16. Explain Exception Filters?

Exception filters will be executed whenever controller methods (actions) throws an exception which is unhandled. Exception filters will implement "IExceptionFilter" interface.

1.1.17. Explain about the new features added in Web API 2.0 version?

  • OWIN
  • Attribute Routing
  • External Authentication
  • Web API OData

1.1.18. How can we pass multiple complex types in Web API?

  • Using ArrayList
  • Newtonsoft JArray

1.1.19. Write a code snippet for passing arraylist in Web API?

ArrayList paramList = new ArrayList();

Category c = new Category { CategoryId = 1, CategoryName = "SmartPhones"};
Product p = new Product { ProductId = 1, Name = "Iphone", Price = 500, CategoryID = 1 };

paramList.Add(c);
paramList.Add(p);

1.1.20. Give an example of MVC Routing?

Below is the sample code snippet to show MVC Routing –

routes.MapRoute(
     name: "MyRoute", //route name
     url: "{controller}/{action}/{id}", //route pattern
     defaults: new
     {
         controller = "a4academicsController",
         action = "a4academicsAction",
         id = UrlParameter.Optional
     }
);

1.1.21. How we can handle errors in Web API?

  • HttpResponseException
  • Exception Filters
  • Registering Exception Filters
  • HttpError

1.1.22. Explain how we can handle error from HttpResponseException?

public TestClass MyTestAction(int id)
{
     TestClass c = repository.Get(id);
     if (c == null)
     {
          throw new HttpResponseException(HttpStatusCode.NotFound);
     }
     return c;
}
HttpResponseMessage myresponse = new HttpResponseMessage(HttpStatusCode.Unauthorized);
myresponse.RequestMessage = Request;
myresponse.ReasonPhrase = ReasonPhrase;

1.1.23. How to register Web API exception filters?

  • From Action
  • From Controller
  • Global registration

1.1.24. Write a code snippet to register exception filters from action?

[NotImplExceptionFilter]
public TestCustomer GetMyTestCustomer(int custid)
{
    //Your code goes here
}

1.1.25. Write a code snippet to register exception filters from controller?

[NotImplExceptionFilter]
public class TestCustomerController : Controller
{
    //Your code goes here
}

1.1.26. Write a code snippet to register exception filters globally?

GlobalConfiguration.Configuration.Filters.Add(new MyTestCustomerStore.NotImplExceptionFilterAttribute());

1.1.27. How to handle error using HttpError?

HttpError will be used to throw the error info in response body. CreateErrorResponse method is used along with this, which is an extension method defined in "HttpRequestMessageExtensions".

1.1.28. Write a code snippet to show how we can return 404 error from HttpError?

string message = string.Format("TestCustomer id = {0} not found", customerid);
return Request.CreateErrorResponse(HttpStatusCode.NotFound, message);

1.1.29. How to enable tracing in Web API?

in Register method of WebAPIConfig.cs file.

config.EnableSystemDiagnosticsTracing();

1.1.30. Explain how Web API tracing works?

Tracing in Web API done in facade pattern i.e, when tracing for Web API is enabled, Web API will wrap different parts of request pipeline with classes, which performs trace calls.

1.1.31. Explain Authentication in Web API?

Web API authentication will happen in host. In case of IIS it uses Http Modules for authentication or we can write custom Http Modules. When host is used for authentication it used to create principal, which represent security context of the application.

1.1.32. Explain ASP.NET Identity?

This is the new membership system for ASP.NET. This allows to add features of login in our application.

  • One ASP.NET Identity System
  • Persistence Control

1.1.33. What are Authentication Filters in Web API?

Authentication Filter will let you set the authentication scheme for actions or controllers. So this way our application can support various authentication mechanisms.

1.1.34. How to set the Authentication filters in Web API?

Authentication filters can be applied at the controller or action level. Decorate attribute – "IdentityBasicAuthentication" over controller where we have to set the authentication filter.

1.1.35. Explain method – "AuthenticateAsync" in Web API?

"AuthenticateAsync" method will create IPrincipal and will set on request

Task AuthenticateAsync(
    HttpAuthenticationContext mytestcontext,
    CancellationToken mytestcancellationToken
)

1.1.36. Explain method – ChallengeAsync in Web API?

to add authentication challenges to response. Below is the method signature –

Task ChallengeAsync(
    HttpAuthenticationChallengeContext mytestcontext,
    CancellationToken mytestcancellationToken
)

1.1.37. What are media types?

It is also called MIME, which is used to identify the data. In Html, media types is used to describe message format in the body.

1.1.38. List out few media types of HTTP?

  • Image/Png
  • Text/HTML
  • Application/Json

1.1.39. Explain Media Formatters in Web API?

Media Formatters in Web API can be used to read the CLR object from our HTTP body and Media formatters are also used for writing CLR objects of message body of HTTP.

1.1.40. How to serialize read*only properties?

Read*Only properties can be serialized in Web API by setting the value "true" to the property

SerializeReadOnlyTypes of class: DataContractSerializerSettings

1.1.41. How to get Microsoft JSON date format?

Use "DateFormatHandling" property in serializer settings as below

var myjson = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
myjson.SerializerSettings.DateFormatHandling = Newtonsoft.Json.DateFormatHandling.MicrosoftDateFormat;

1.1.42. How to indent the JSON in web API?

var mytestjson = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
mytestjson.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;

1.1.43. How to JSON serialize anonymous and weakly types objects?

Using Newtonsoft.Json.Linq.JObject we can serialize and deserialize weakly typed objects.

1.1.44. What is the use of IgnoreDataMember

By default if the properties are public then those can be serialized and deserialized, if we does not want to serialize the property then decorate the property with this attribute.

1.1.45. How to write indented XML in Web API?

To write the indented xml set "indent" property to true.

1.1.46. How to set Per*Type xml serializer?

We can use method – "SetSerializer". Below is the sample code snippet for using it

var mytestxml = GlobalConfiguration.Configuration.Formatters.XmlFormatter;
// Use XmlSerializer for instances of type "Product"
mytestxml.SetSerializer<Product>(new XmlSerializer(typeof(MyTestCustomer)));

1.1.47. What is UnderPosting and "OverPosting" in Web API?

  • "UnderPosting" When client leaves out some of the properties while binding then it’s called under–posting.
  • "OverPosting" – If the client sends more data than expected in binding then it’s called overposting.

1.1.48. How to handle validation errors in Web API?

Web API will not return error to client automatically on validation failure. So its controller’s duty to check the model state and response to that. We can create a custom action filter for handling the same.

1.1.49. Give an example of creating custom action filter in Web API?

public class MyCustomModelAttribute : ActionFilterAttribute
{
     public override void OnActionExecuting(HttpActionContext actionContext)
     {
         if (actionContext.ModelState.IsValid == false)
         {
         //Code goes here
         }
     }
}

In case validation fails here it returns HTTP response which contains validation errors.

1.1.50. How to apply custom action filter in WebAPI.config?

Add a new action filter in "Register" method as shown *

public static class WebApiConfig
{
     public static void Register(HttpConfiguration config)
     {
         config.Filters.Add(new MyCustomModelAttribute());
     }
}

How to set the custom action filter in action methods in Web API?

Below is the sample code of action with custom action filter –

public class MyCustomerTestController : ApiController
{
    [MyCustomModelAttribute]
    public HttpResponseMessage Post(MyTestCustomer customer)
    {
    }
}

1.1.51. What is BSON in Web API?

It’s is a binary serialization format. "BSON" stands for "Binary JSON". BSON serializes objects to key*value pair as in JSON. Its light weight and its fast in encode/decode.

1.1.52. How to enable BSON in server?

Add "BsonMediaTypeFormatter" in WebAPI.config as shown below

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
           config.Formatters.Add(new BsonMediaTypeFormatter());
    }
}

1.1.53. How parameter binding works in Web API?

  • If it is simple parameters like – bool, int, double etc. then value will be obtained from the URL.
  • Value read from message body in case of complex types.

1.1.54. Why to use "FromUri" in Web API?

In Web API to read complex types from URL we will use "FromUri" attribute to the parameter in action method. Eg:

public MyValuesController : ApiController
{
     public HttpResponseMessage Get([FromUri] MyCustomer c) { ... }
}

1.1.55. Why to use "FromBody" in Web API?

This attribute is used to force Web API to read the simple type from message body. "FromBody" attribute is along with parameter. Eg:

public HttpResponseMessage Post([FromBody] int customerid, [FromBody] string customername) { ... }

1.1.56. Why to use "IValueprovider" interface in Web API?

This interface is used to implement custom value provider.

Copyright © Guanghui Wang all right reserved,powered by GitbookFile Modified: 2019-08-25 13:56:34

results matching ""

    No results matching ""