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

Tan Woon How

He is a learner and know little around .Net and Java. He learned and share if you see his mistake... feel free to comment and laugh at him... and also please help to correct him.

You may also like...

  • 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.

  • 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.