How easy to start with ASP.Net WEB API 2.0?




My answer to this title is. Super easy!!!, Yes i mean, Z E R O coding. You do not need to code a line and your WebAPI are ready for you to deploy into production. That’s cool!!!

Todo
The object of this tutorial to show how to create a CRUD Web API with ZERO coding ;).

Tools used
1. Microsoft Visual Studio 2013, C#.
2. Fiddler
3. SQL Server 2012.

How easy to start with ASP .Net WEB API 2.0?

Database – Table Structure
We will start the tutorial from the database and I always try to use the same table structure for all my tutorial, nothing special, I just lazy to think ONLY :P., That’s all! Other than that, why should we need to use a different table for just show you how it work. ๐Ÿ™‚

So, Let’s explore how are we going to do this.
1. Run this SQL Script and it will create Institute database with 1 Student table with data like shown in above image

2. After run the script, make sure you have the database and table ready for the next step.
table structure

Code
1. Open up your MS. VS 2013, Let’s start create the project File > New > Project, and type in WebAPI as project name.

2. Click OK, another dialog popup and choose a Empty template and tick Web API.

3. I want to change the URL to http://localhost:port/institute/, later when we deploy into IIS it will look odd when we have 2 api in the URL , so go to Solution Explorer > App_Start > WebApiConfig.cs, and change the code to like the highlighted line

So far still no code yet :), as above just change name not code (Not count :P).

4. Let’s continue to setup on database connectivity, right click on solution explorer and Add New Item > Choose Data > ADO.net Entity Model, and type Institute.

5. From the Entity Data Model Wizard > Choose EF Designer from Database > Next > Click New Connection > Fill in the database connection and click Test Connection to make sure the setting is fine.

6. In this screeen, i prefer to choose save sensitive data into config so tick “Yes”.

7. Then Click Next to chose Entity Framework 6.X

8. Lastly choose table and click Finish. and you should a file created like below images.

9. Now, go to Controllers > Right Click > New Scaffolded item > Choose Web API 2 Controller with actions, using Entity Framework > Click Add.

10. Fill in the information like this

and you will see StudentsController.cs in controller folder. :D. Hooray!!!, you have complete your WebAPI 2.0!!! From the code generated, you could see we have the following and these are all we need!!!

    • i. GET: api/Students
      ii. GET: api/Students/5
      iii. PUT: api/Students/5
      iv. POST: api/Students
      v. DELETE: api/Students/5
  • 11. We need to make sure the functions are working, again i’m lazy bum,so to make a client app to test this will kill me in second, so we use Fiddler!!! First, run your WebAPI and then launch Fiddler, and go to Composer and we going to test 1 by 1
    i. GET: api/Students

    ii. GET: api/Students/2

    iii. PUT: api/Students/2

    iv. POST: api/Students

    v. DELETE: api/Students/3

    Yeah!!! Done.

    Deploy into IIS
    1. We need to add 1 more setting into Web.Config before deploy our solution into IIS, if you miss this step, you will get error 405, Method not allowed when you invoke DELETE/PUT/POST function. Go to Web.Config and add these lines

    1. Go to IIS, press Windows + R, type inetmgr > Enter, and click on Default Web Site > Add Application and key in information as below image
    2. Browse the deployed solution in browser to make sure it’s fine and you should expect result as below image

    Optional – Output As Json
    1. In WebApi, we are allow to control the output format and it is either XML or JSON format, and above tutorial that we did so far is XML output, so if you like to change the output format you just need to add 1 more line into App_Start/WebApiConfig.cs and the changes will be as below highlighted line

    2. The result will look different if you browse again, as you compare the size of data being display on the browser JSON format is much lesser than XML format.

    In these days, the smartphone has been widely used and one of the most common function is request data from the server. During data transferring process, data may be lost due to many reasons, so to reduce the chances of this happened, one of the thing we could do is reduce the size of each packet to be transfer. Thus, we recommend you use JSON as output when transferring data.

    What’s Next

    In the next post, I will show you how to request data from server from the Smartphone, How to call ASP.Net Web API from Android Studio?, (meaning I still need to build a client :P.) And this tutorial will be our server for the next post, So stay tune!!!

    OK, That’s all for me, if you have any question, please comment and I will reply as soon as possible. Hope you like the post.




    JOIN OUR NEWSLETTER
    In case you want to get any future post please allowed us deliver new posts direct into your inbox Or follow us on
    We hate spam. Your email address will not be sold or shared with anyone else.
    • Fernanda

      where i can download the code?

    • ื—ื ื” ืงืื”ืŸ

      Im trying to run your code on vs 2012 and he doesnt recognize some functions is 2013 the solution?

      • Tan Woon How

        I think you missing some reference in your machine.

      • Tan Woon How

        I think you missing some reference in your machine. Make sure you have EF install from Nuget if you don’t have one. As no error provided, i’m not sure what you have missing. So refer to this image for any missing reference

        • ื—ื ื” ืงืื”ืŸ

          how come in the webApiConfig you put in the routTamplate: institute and not api?

          • Tan Woon How

            Sorry i miss this one

            You mean this block?
            config.Routes.MapHttpRoute(
            name: “DefaultApi”,
            routeTemplate: “institute/{controller}/{id}”,
            defaults: new { id = RouteParameter.Optional }
            );

            because i don’t want the URL to look like this when deployed http://localhost:port/api/api/

            • ื—ื ื” ืงืื”ืŸ

              got it, thanks!

      • ื—ื ื” ืงืื”ืŸ

        Ihane all thr references and EF from NuGet
        here are some of the things he’s pointing an eror on

    • advanex 123

      When I deployed into IIS, I got following errors occurred (screenshot). Please advice.
      Thanks

      • advanex 123

        This error will explain more details

        • Tan Woon How

          Because look at the error, may i know do you executed the query from above? and do you configure the web.config file for you database location? It seem to me some issue with your database connection setting.

          For the error, i google it and found this http://stackoverflow.com/questions/21641435/error-no-entity-framework-provider-found-for-the-ado-net-provider-with-invarian

          and see will this able to solve it?

          • advanex 123

            Sir, I tried different ways but still can’t solve it =(
            below here is my Web.config. Please help me take a look.Thanks.

            <!– –>

            • advanex 123

              This is the WebApiConfig.cs

              using System;

              using System.Collections.Generic;

              using System.Linq;

              using System.Web.Http;

              using System.Net.Http.Headers;

              namespace WebAPI

              {

              public static class WebApiConfig

              {

              public static void Register(HttpConfiguration config)

              {

              // Web API configuration and services

              //test

              var json = config.Formatters.JsonFormatter;

              json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;

              config.Formatters.Remove(config.Formatters.XmlFormatter);

              // Web API routes

              config.MapHttpAttributeRoutes();

              config.Routes.MapHttpRoute(

              name: “DefaultApi”,

              // routeTemplate: “api/{controller}/{id}”,

              routeTemplate: “institute/{controller}/{id}”,

              defaults: new { id = RouteParameter.Optional }

              );

              //change xml to JSON output

              config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue(“text/html”));

              }

              }

              }

            • Tan Woon How

              Hi,
              I can’t see any error from the code and config.

              So if you don’t mind to send me your code and database to admin[a]instinctcoder.com, let me have a look.

            • advanex 123

              Hi Sri,
              i did some screenshot and did documentation also: Pls download below. Thanks.

              https://www.dropbox.com/s/hzkembyqq2bkhmj/WebAPI.zip?dl=0

            • Tan Woon How

              Hi
              I checked the code and executed code from the files you sent over is working fine.

              1) I noticed you deployed the solution on desktop, i recommend you dont as you required to set permission on the folder in order to access. Prefer to set either C:inetpubwwwroot, or other folder Like C:Folder.

              2) I tried to simulate the error that you get, it seem like something to do with your database and application pool setting. I’m not in your environment can’t tell you what exactly goes wrong. But from what i tested just now, my machine just formatted so is good for to test it out and i got only SSDT in my machine, and the security for this instance come very limited user access for IIS, so you need to configure your ApplicationPool as mentioned in this http://stackoverflow.com/questions/14662271/unable-to-open-database-when-website-hosted-in-iis, which mentioned by Nicholas. and also add NT AUTHORITYNETWORK SERVICE user under Security for your database. Hope that helps.

              Alternatively, if possible, try install a new SQL instance and make sure you have the security login as below image (the upper one).

            • advanex 123

              Dear Sir, I got this error come out after I followed your instructions:

              An error has occurred.The ‘ObjectContent1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'.System.InvalidOperationExceptionAn error has occurred.The 'DbProviderFactories' section can only appear once per config file.System.Configuration.ConfigurationErrorsException at System.Configuration.BaseConfigurationRecord.EvaluateOne(String[] keys, SectionInput input, Boolean isTrusted, FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentResult)

              at System.Configuration.BaseConfigurationRecord.Evaluate(FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentResult, Boolean getLkg, Boolean getRuntimeObject, Object& result, Object& resultRuntimeObject)

              at System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String configKey, Boolean getLkg, Boolean checkPermission, Boolean getRuntimeObject, Boolean requestIsHere, Object& result, Object& resultRuntimeObject)

              at System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String configKey, Boolean getLkg, Boolean checkPermission, Boolean getRuntimeObject, Boolean requestIsHere, Object& result, Object& resultRuntimeObject)

              at System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String configKey, Boolean getLkg, Boolean checkPermission, Boolean getRuntimeObject, Boolean requestIsHere, Object& result, Object& resultRuntimeObject)

              at System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String configKey, Boolean getLkg, Boolean checkPermission, Boolean getRuntimeObject, Boolean requestIsHere, Object& result, Object& resultRuntimeObject)

              at System.Configuration.BaseConfigurationRecord.GetSection(String configKey)

              at System.Configuration.PrivilegedConfigurationManager.GetSection(String sectionName)

              at System.Data.Common.DbProviderFactories.Initialize()

              at System.Data.Common.DbProviderFactories.GetFactory(String providerInvariantName)

              at System.Data.Entity.Infrastructure.DependencyResolution.DefaultProviderFactoryResolver.GetService(Type type, Object key, Func3 handleFailedLookup)

              at System.Collections.Concurrent.ConcurrentDictionary2.GetOrAdd(TKey key, Func2 valueFactory)

              at System.Linq.Enumerable.WhereSelectArrayIterator2.MoveNext()

              at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable1 source, Func2 predicate)

              at System.Data.Entity.Infrastructure.DependencyResolution.RootDependencyResolver.GetService(Type type, Object key)

              at System.Linq.Enumerable.WhereSelectArrayIterator2.MoveNext()

              at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable1 source, Func2 predicate)

              at System.Data.Entity.Infrastructure.DependencyResolution.CompositeResolver2.GetService(Type type, Object key)

              at System.Data.Entity.Infrastructure.DependencyResolution.DbDependencyResolverExtensions.GetService[T](IDbDependencyResolver resolver, Object key)

              at System.Data.Entity.Core.EntityClient.EntityConnection.ChangeConnectionString(String newConnectionString)

              at System.Data.Entity.Internal.LazyInternalConnection.InitializeFromConnectionStringSetting(ConnectionStringSettings appConfigConnection)

              at System.Data.Entity.Internal.LazyInternalConnection.TryInitializeFromAppConfig(String name, AppConfig config)

              at System.Data.Entity.Internal.LazyInternalConnection.Initialize()

              at System.Data.Entity.Internal.LazyInternalConnection.CreateObjectContextFromConnectionModel()

              at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()

              at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)

              at System.Data.Entity.Internal.Linq.InternalSet1.Initialize()

              at System.Data.Entity.Internal.Linq.InternalSet`1.GetEnumerator()

              at WriteArrayOfStudentToXml(XmlWriterDelegator , Object , XmlObjectSerializerWriteContext , CollectionDataContract )

              at System.Runtime.Serialization.CollectionDataContract.WriteXmlValue(XmlWriterDelegator xmlWriter, Object obj, XmlObjectSerializerWriteContext context)

              at System.Runtime.Serialization.XmlObjectSerializerWriteContext.WriteDataContractValue(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle declaredTypeHandle)

              at System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeWithoutXsiType(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle declaredTypeHandle)

              at System.Runtime.Serialization.DataContractSerializer.InternalWriteObjectContent(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver)

              at System.Runtime.Serialization.DataContractSerializer.InternalWriteObject(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver)

              at System.Runtime.Serialization.XmlObjectSerializer.WriteObjectHandleExceptions(XmlWriterDelegator writer, Object graph, DataContractResolver dataContractResolver)

              at System.Runtime.Serialization.DataContractSerializer.WriteObject(XmlWriter writer, Object graph)

              at System.Net.Http.Formatting.XmlMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, HttpContent content)

              at System.Net.Http.Formatting.XmlMediaTypeFormatter.WriteToStreamAsync(Type type, Object value, Stream writeStream, HttpContent content, TransportContext transportContext, CancellationToken cancellationToken)

              — End of stack trace from previous location where exception was thrown —

              at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)

              at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)

              at System.Web.Http.WebHost.HttpControllerHandler.d__1b.MoveNext()

            • Tan Woon How
            • Thein Min

              Hi sir, I got the answer already
              the reasons why i got this is because my IIS using .net v4.0 and my visual studio tragetFramework is 4.5.
              That’s why I got this kind of errors come out.
              Appreciate your help and Have a nice day.
              Now I will move forward your next tutorial : http://instinctcoder.com/how-to-call-asp-net-web-api-from-android-studio/
              Thanks.

            • Tan Woon How

              Damn….you…. (speechless)

            • advanex 123

              My apologies.
              Due to lack of my experience in implementing this. =D
              Thz anyway.

            • Zee

              whats the solution….. Can you share with all of us??

            • Tan Woon How

              Cool. Enjoy

    • Ivan

      Hello, I have a problem when I deploy into IIS. When I browse the deployed solutioin I get the error showed in the image below. When I run the app with Visual Studio I can view the data perfectly, so I don’t know what’s the problem. Thanks for the tutorial ๐Ÿ™‚

      • Tan Woon How

        This is permission issue. Chekc the permission of the file and folder and also please make sure you grant for network service. For details you could refer to herehttp://stackoverflow.com/questions/19438204/iis-suddenly-gets-access-denied-when-attempting-to-read-web-config

        If you found it too complicated at start just grant everyone permission . ;). But is not advise to do so.

    • Ivan

      Hello, I have a problem when I deploy into IIS. When I browse the deployed solutioin I get the error showed in the image below. When I run the app with Visual Studio I can view the data perfectly, so I don’t know what’s the problem. Thanks for the tutorial

    • ะะฝั‚ะพะฝ ะ‘ัƒัˆะธะฝ

      Thank you for the lesson! But it would be nice to consider possible problems with access to the database from DefaultAppPul application. So, I had to login to register for IIS APPOOLeDefaultAppul to access the database. So far, the group membership have db_datareader, may need to be extended ..

      • Tan Woon How

        Hmmm.. thanks for the info. But i did not encounter this issue.