Building an ASP.NET Web Api RESTful service

You may also like...

41 Responses

  1. Sujitkumar says:

    Very Nice tutorial. Really helpful for a lot of information about ASP …. Please keep update some more…………

  2. Mail says:

    Hi,
    would you mind in republishing this tutorial for ASP.NET Core 1.0 on Linux? 🙂

  3. Ingic says:

    one thing i want to ask..when we post data using Advance Rest Client.where will be the data stored?
    I mean the data we have entered in Advance Rest Client …will be stored in class file or else where..?

  4. redsuitee says:

    it helps a lot!! thanks man!

  5. questions1357@gmail.com says:

    Very Useful code. Is there any way to catch Sql Exceptions and send back to RESTApi client?

  6. Terry says:

    Zoran,

    I am a web forms, visual basic developer who is just starting to get into the MVC and C# world. I am trying to follow through your example but do not know how to create the product class exactly. Would you be able to explain that class a little more and possible send the full class code for that class?

    thank you!

  7. Anonymous says:

    Hi Zoran,

    Can you please tell me how to convert the RESTful WEB API made in MVC4 into SOAP web service.

    • Hi,
      As far as I know there is nothing that can automatically convert your REST service into a SOAP web service.
      ASP.NET Web API doesn’t support SOAP so for this you must use WCF framework.

      Obviously, I don’t know the context of your project, but the steps I would follow are:
      1) Extract the business logic of your REST services. So, database connections, data manipulation, etc… to be placed into a separate library
      2) Start creating WCF Services and call the library created in the step 1)

      in this way you can share the code between WCF and REST services (if you need both of them).

      Another alternative would be to use ServiceStack framework, and move toward REST/SOAP based services without having to write individually the different types of services. For the SOAP support you can find more info here: https://github.com/ServiceStack/ServiceStack/wiki/SOAP-support

      Let me know…

  8. Naye says:

    Hi Zoran,

    When i run your project ‘out of the box’ from VS 2012 – get the following error:

    “HTTP Error 403.14 – Forbidden” – “A default document is not configured for the requested URL, and directory browsing is not enabled on the server.”

    • I tried it out and I got the same error. So, you made me worry, as I wrote this article a while ago 🙂
      Actually, this is simply because there is no default value in the VS 2012 web service that would point to api/product.
      However, simply change the URL in the browser to http://localhost:34133/api/product and you will get the result 🙂

      Cheers,
      Zoran

  9. Lelala says:

    Thanks for that tutorial – reading yours, i found the bug in my own code 🙂

  10. Zied says:

    Hi Zoran, Thanks for the post, i implemented it using Entity framework with an SQL database and it works like a shine, i just was wondering how it goes in real world when a user sends data in the post method when i inserted them in the raw input ?
    Thanks

    • Hi Zied,
      I guess you front end is a Asp.NET or Asp.NET MVC, or in any case it’s a web front end.
      In that case you can create a simple form where the user will fill all the information you need, and then you either post the content of the form to your service, or you can prepare your data, before sending them to the server, by using Javascript. I suggest you use JQuery as it is very versatile and useful.
      Here you have some examples of how to do that
      http://api.jquery.com/jQuery.post/

      I hope it helps.
      If you find a good solution, please post it here 🙂 for our knowledge.

      Zoran

      • Zied says:

        Hello, in fact the action is very simple, using Rest service in the final application (inetgrating RestSharp) will give users options to add parameters and we will have smthing like this

        RestRequest request = new RestRequest();

        request.Method = Method.POST;

        request.AddParameter(“parametername”,”Data”);
        can’t beleive how i forgot that!
        i have an other question about the Put Method, i tested and it works but values doesn’t change !! any idea please?
        Thanks

  11. Ron Lutsky says:

    Thanks a lot for this article.
    Could you please explain why you use POST to create a new product and not PUT as you stated in “Creates a Resource. Use PUT if you are sending the full content of the specified resource (URL).”

    • Hi Ron,
      Thanks for your comment. Actually the PUT vs POST causes a lot of confusion.
      In reality you could use both for Creation and Update, it just depends how you want to use it, based on the URI to which one are you Posting or Putting.

      I think that this article contains a good answer to your question:
      http://stackoverflow.com/questions/630453/put-vs-post-in-rest

      • Zied says:

        Hi Zoran,
        thanks for this tuto, i followed it and it works like shine with Entity Framework, i just wonderring in the post mode how the user can send data in the real world, for my part i created the service and passed the data in the input Raw to test it but when it comes to a simple user how will he pass parameters to Insert them ?
        Thanks Again 🙂

  12. Ron Lutsky says:

    Great.
    At the beginning you say that PUT:
    “Creates a Resource. Use PUT if you are sending the full content of the specified resource (URL).”
    But you use POST to create a product in the code example.
    Can you explain this please? Thanks a lot 🙂

  13. Kirill says:

    Thanks for tutorial. Is it possible to put product ID as attribute, so that xml output was ?

  14. Thanks Zoran for taking time to write this wonderful blog!!!

  15. vinaymurthy says:

    how to achieve security with restful api in .net

  16. darshan says:

    one thing i want to ask..when we post data using Advance Rest Client.where will be the data stored?
    I mean the data we have entered in Advance Rest Client …will be stored in class file or else where..?

    • Hi Darshan,
      I am not quite sure if I understood your question. Advanced Rest Client is just a client application that enables to post JSON or XML to a RESTful service, nothing more. So, that data is not “saved” anywhere really but just transmitted to the service. The RESTful service, before receiving the JSON data, through some filters will receive the deserialized JSON/XML object, for which one obviously you would need to have a class.
      If you have perhaps a more specific question I will be happy to try to help you.

  17. Rambabu says:

    It’s really helpful.
    Thanks a lot!!!!!!

  18. Naresh says:

    Hi Zoran,

    i am getting below error:

    An error has occurred.

    The ‘ObjectContent`1’ type failed to serialize the response body for content type ‘application/xml; charset=utf-8’.

    System.InvalidOperationException

    An error has occurred.

    The operation cannot be completed because the DbContext has been disposed.

    System.InvalidOperationException

    at System.Data.Entity.Internal.InternalContext.CheckContextNotDisposed() at System.Data.Entity.Internal.LazyInternalContext.InitializeContext() at System.Data.Entity.Internal.InternalContext.Initialize() at System.Data.Entity.Internal.Linq.InternalQuery`1.GetEnumerator() at System.Data.Entity.Infrastructure.DbQuery`1.System.Collections.Generic.IEnumerable.GetEnumerator() at WriteArrayOfLeadToXml(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.SerializeAndVerifyType(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, Boolean verifyKnownType, RuntimeTypeHandle declaredTypeHandle, Type declaredType) at System.Runtime.Serialization.XmlObjectSerializerWriteContext.SerializeWithXsiTypeAtTopLevel(DataContract dataContract, XmlWriterDelegator xmlWriter, Object obj, RuntimeTypeHandle originalDeclaredTypeHandle, Type graphType) 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.c__DisplayClass7.b__6() at System.Threading.Tasks.TaskHelpers.RunSynchronously(Action action, CancellationToken token)

    Please , correct me , if i miss anything.

    Thanks.

  19. Nikunj Dhawan says:

    This is very helpful!

  20. Dev says:

    Thanks very helpful!

  21. slareau says:

    I have downloaded the code and run it. I can enter a uri and run the app and get results bun I am unable to get the form in this example. What am I doing wrong?

  22. jon says:

    That’s exactly the problem I’m having. I’m new to Web API’s, Ioc and DI and I’m having difficulty combining it all into one solution. There’s a lot of examples of IoC and DI OR Web API’s, but nothing with a solid architecture (i.e. decoupled code) combining them all.

    Anyways, thank you so much for your time!

  23. jon says:

    Would you be able to provide sample code with an actual database please? I’ve been really struggling with the full concept. Thank you!

    • Hi Jon,
      For reason of brevity of the article, I was only pointing out the changes and what should be done in order to create a service, without actually going deeper into the database connectivity.
      If you check the source code (the example project that you may download) there is a class called ProductContext where I am actually adding in memory some example data, just for the purpose of trying out the solution.
      Depending on the database and the underlying technology for accessing database you are using the “solution” would potentially change. So there is no one single answer.

      As a potential solution to the existing example
      1) You may simply add the connection to the database directly in the ProductContext class and query your database from there. Just to see how it works.

      But in an real world example I would use some architecturally more interesting patterns like:
      – Repository Pattern (each repository would have single responsibility and hold access to the db for a specific object),
      – Interface segregation: You don’t want to couple your Service with the database logic implementation, so the coupling between objects should be done through interfaces.
      – Inversion Of Control : To actually inject the implementation object at run time.

      Try checking this forum for further info about Setting up web api to pull data from a database using Entity Framework in case you are using SQL Server and want to use Entity Framework.

      When i have a bit more time, which I never really have 🙂 I will try to extend this solution with what said above.

Leave a Reply

masucci@mailxu.com delore@mailxu.com