Wednesday, April 27, 2016

Web Api

Web Api Session


//create new class and add following code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http.WebHost;
using System.Web.Routing;
using System.Web.SessionState;

namespace AAA.Controllers
{
    public class SessionableControllerHandler : HttpControllerHandler, IRequiresSessionState
    {
        public SessionableControllerHandler(RouteData routeData)
            : base(routeData)
        { }
    }
    public class SessionStateRouteHandler : IRouteHandler
    {
        IHttpHandler IRouteHandler.GetHttpHandler(RequestContext requestContext)
        {
            return new SessionableControllerHandler(requestContext.RouteData);
        }
    }
}

-----------
Change default web api router as following


using AAA.Controllers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.Routing;

namespace AAA
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();

            RouteTable.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
).RouteHandler = new SessionStateRouteHandler();
        }
    }
}

-----------------------------------
create and access session as following


  // GET api/<controller>
        public IEnumerable<string> Get()
        {
            if ((HttpContext.Current.Session["SomeData"] as string) == null)
            {
                HttpContext.Current.Session["SomeData"] = "Hello from session";
            }
            return new string[] { "value1", "value2" };
        }

        // GET api/<controller>/5
        public string Get(int id)
        {
            return (HttpContext.Current.Session["SomeData"] as string);
        }


//////////////////////////////////////////////////


Web Api Documentation

01) create new web api project with template .
   it will include helpPage as following

\


02) Then enable documentation


  1.   set documentation path in project (project->proporties->build-->output--> xml documantation file ).
  2. set path to App_Data
  3. change    HelpPageConfig and set following to same path.
    config.SetDocumentationProvider(new XmlDocumentationProvider
    (HttpContext.Current.Server.MapPath("~/App_Data/DependancyInjections.xml")));


     now documentation xml file is save on the App_Data folder

/// <summary>
        /// Add Customer
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public string Add()
        {
            cus.Add();
            return "added";
        }




/////

Authorize filter life cycle.




//////////////////

web api return type

web api has 4 return types


  1. void
  2. IHttpActionRersult
  3. HttpResponseMessage
  4. another type

/////////////////////

Error and Exception handling in web api


public class ExceptionsController : ApiController
    {
 
        public async Task<IHttpActionResult> GetItem(int id)
        {
 
            throw new HttpResponseException(new HttpResponseMessage
            {
                StatusCode = HttpStatusCode.Forbidden,
                ReasonPhrase = "item not found",
                Content = new StringContent(string.Format("No product with ID = {0}", id)),
 
            });
        }
        public async Task<HttpResponseMessage> GetProduct(int id)
        {
            if (id == 1)
            {
                var message = string.Format("Product with id = {0} not found", id);
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, message);
            }
            else
            {
                return Request.CreateResponse(HttpStatusCode.OK, new { name = "pencile", id = 2 });
            }
        }
    }

Error Handling in web api 

  • HttpResponseException
    public async Task<IHttpActionResult> GetItem(int id)
           {
     
               throw new HttpResponseException(new HttpResponseMessage
               {
                   StatusCode = HttpStatusCode.Forbidden,
                   ReasonPhrase = "item not found",
                   Content = new StringContent(string.Format("No product with ID = {0}", id)),
     
               });
           }
  • Exception Filters
  • Registering Exception Filters
  • HttpError.
    public async Task<HttpResponseMessage> GetProduct(int id)
          {
              if (id == 1)
              {
                  var message = string.Format("Product with id = {0} not found", id);
                  return Request.CreateErrorResponse(HttpStatusCode.NotFound, message);
              }
              else
              {
                  return Request.CreateResponse(HttpStatusCode.OK, new { name = "pencile", id = 2 });
              }
          }
////////////////////////////////

Tracing



public HttpResponseMessage GetTrace() {
 
            ITraceWriter x = Configuration.Services.GetTraceWriter();
            x.Trace(Request, "Category", TraceLevel.Error, $"this is test");
 
            return null;
        }


public static class WebApiConfig
   {
       public static void Register(HttpConfiguration config)
       {
        config.EnableSystemDiagnosticsTracing();
        traceWriter.IsVerbose = true;

       }
}

///////////////////////////

Enable cors (Cross origin resource sharing)


  1. instrall cors nuget
  2. add following code to webApiConfig--> register method

public static class WebApiConfig
   {
       public static void Register(HttpConfiguration config)
       {
        config.EnableCors();
         config.EnableCors(New EnableCrosAtribute("*",""));

       }
}


/////////////////////////
INTERVIEW QUESTIONS


  1. what is web api.
    it is service run at iis, handle client http requests.






CS Events