0

I am new to Web Api world and I see a lot of potential for in the new MVC 4 Web Api. I have generated a WCF Web Service but was planning to get to know Web-APIs and their web service capabilities. Now, is MVC 4 Web-Api Service more as front end? I wrote a sample Service by following some examples online in MVC 4 Web Api but how do I consume the Service in just a basic console app? I have figured out the only way to consume it is by using HttpClient are there other ways? I am used to ASP.NET Web Service and WCF Web Service as where you reference it as a service in your references and then you are able to see all of its objects, properties to make appropriate calls.

What happens if web-api is requesting a object "Task" for post method as an example how am I able to fill an object "Task" and post it back to the web-api? As in WCF I am able to see that "Task" object and its properties because of WSDL so I am able to fill them and send it back to the service how is that done in web-api service?

The webservice would be used internally is it worth it to have an web-api service?

Thank you so much for helping clearing some question of what I have about web-api services.

Nick Manojlovic
  • 1,171
  • 10
  • 30
  • 49
  • can you clear up the question a little, it's quite hard to read. it also seems there are several questions within, try to narrow down your question – dove Nov 01 '12 at 13:36
  • @dove sorry :) I was in a hurry to type up a question as I was heading to a meeting I hope its better now? – Nick Manojlovic Nov 01 '12 at 14:03
  • Jumping straight into the question of internal application and if it is worth doing a web-api-service. I have a question for you. Is this just going to be used as a web site? If so, then I would not do a web-api service and just go with a MVC design. If you plan to use the service with other platform (like mobile), then yes. You will need a data payload to that. When doing a website using MVC, the standard policy of doing everything in one project could get heavy as the app grows. So you can customize to different projects as needed to make it nimble. – Steven Nov 01 '12 at 14:14
  • There is a detailed description for subject on codeproject:http://www.codeproject.com/Articles/826359/Consuming-ASP-NET-WEB-API-using-ASP-NET-MVC-and-Re – Gaurav Arora Jan 19 '15 at 08:45

2 Answers2

2

---Edit as per Comment---

This screenshot shows a possible structure which you can approach. Of course, you can take a design that best suit your application.

Sample MVC Application

So ControllerLib is a separate Class Library project which is brought into the main project as a Service Reference (which is not shown in the screenshot but should be inside the References folder of the SecondMVCApplication project). The two controller file (HomeController.cs and LocationController.cs is a controller file that implemented the Controller class, which is the same thing as a Controller file when you create a new MVC4 application using the template)

So for your question regarding if there is a SVC file. NO. In MVC 4, there is no such thing as a SVC file whether the application is one project or a combination of multiple project (unless I am mistaken). Inside the SecondMVCApplication, there is a file called RouteConfig.cs which holds the routing URL and as long as you add the Service Reference and there controller function exists. The code will run. Also the sample screenshot I showed also includes a WebApiConfig.cs file. You can use that file to do API stuff for mobile if you need. So, the regular RouteConfig.cs handles website request and the WebApiConfig.cs handles API request.

Good to Note: If you are using a Model project as a separate project (which I know you will as it is a M-V-C project...DUH!!). Make sure you put your connection string inside the web.config main project (in this case, the SecondMVCApplication). I remember I was stuck in this problem for 3 days (8 hours each) trying to fix this problem. Hope you don't run into it.

---End Edit---

The following answer to your question is mostly based on my knowledge and may or may not be true to all users.

  • Is MVC 4 Web-Api Service more as front end?

This depends on how you look at it. Typically, a Web-API service is more suited for creating back-end service to provide a data payload to different platforms, like mobile, desktop apps and so on. However, a MVC4 Internet Application will have front-end aspects in them, namely the Views, which end-users sees.

  • How do I consume the Service in just a basic console app?

AFAIK, there is two way to do this. One if to consume the APIs as a Service Reference. Another is to use HTTP operation (which I will mention in your question regarding the HTTP client and reserve this answer using the Service Reference method).

This depends on how your application is done. Like I said, if it is a website, your MVC pattern will not need to do anything, but the Models, Views and Controllers all are designed to work together without using any service.

Although, as I mentioned in the comments to the questions, if it is a big application then you will need to break them into different projects that will make the app modular and nimble. So you will end up creating different Service Library. If you go down the Service Library road, then you just make use of the Add Reference option to bring in your API/Projects/Whatever-you-call-it into the project. (For this, I normally put all project inside a single solution and let Visual Studio manage the build order as I am lazy to write up a build script).

Similarly, the same logic could be applied when consuming your web service in a console app.

  • I have figured out the only way to consume it is by using HttpClient are there other ways?

One way to consume web APIs is using HTTP. Are you aware of how to write http request headers and handle http response. If so, this is the second way I mentioned. You call the web service through it's URL and then get the data and do whatever work. If your answer to use http in console app is NO, then look at this post: Create HTTP post request and receive response using C# console application

  • What happens if web-api is requesting a object "Task" for post method as an example how am I able to fill an object "Task" and post it back to the web-api?

I think I indirectly answered this in your previous answer (assuming you are going to take the HTTP road). If not, then comment and I'll see if I can find some resource for you.

  • The webservice would be used internally is it worth it to have an web-api service?

I sort of answered this in the comment to the question. Ask if you need clarification.

Hope all this helps.

Community
  • 1
  • 1
Steven
  • 974
  • 6
  • 18
  • thank you very much for answering the questions. I still have couple more :). Do you have to have the SVC File in your MVC to make it a service or is having it as a controller enough? Because when I take my URL and try to add it as a reference it does not work? – Nick Manojlovic Nov 01 '12 at 16:27
  • Look at the answer again for the edit to answer your question. What I explained that your URL routing will sit inside your main project and the controller inside a seperate library. **NOTE:** This is one approach, it doesn't mean that you have to follow this. Everyone have their own way of doing it. This is just simplified for you. – Steven Nov 01 '12 at 17:36
  • FYI, a project that I worked on, we eventually went with 4+ different project. A model (DAL) project, a Business Logic Project, Multiple Controller project (they are there to know which business logic to call when a URL is request because we don't want to repeat code that is required in more than one controller and you should never call another controller from a controller. Finally, there is the View project that handle presentation stuff. – Steven Nov 01 '12 at 17:38
  • Steven, when I try to add a service reference to http://localhost/wmwebservicetest/api/CAD to my console app it gives me an error saying there is no recognized document type. Any Idea of what am I doing wrong? Here is the image link to my sln http://img4.imageshack.us/img4/3595/captureumcq.png – Nick Manojlovic Nov 01 '12 at 18:18
  • and here is the link for the error: http://img641.imageshack.us/img641/4097/capture1rf.png – Nick Manojlovic Nov 01 '12 at 18:27
  • This may or may not be related to you. But is your controller service class called `WMCommon`? If so, why is it in VB and your website is in C#? I don't know if this will cause any error. – Steven Nov 01 '12 at 18:27
  • WMCommon is like a data access layer we have that contains models and controllers is been initially started in VB the plan is to rewrite it to C#. – Nick Manojlovic Nov 01 '12 at 18:30
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/18935/discussion-between-nick-and-steven) – Nick Manojlovic Nov 01 '12 at 18:30
  • cant do chat. My corporate networks blocks the IP to the chat. – Steven Nov 01 '12 at 18:33
  • You would want to look at this links below for section of breaking the solution into separate projects: http://msdn.microsoft.com/en-us/magazine/jj190803.aspx – Steven Nov 01 '12 at 18:35
  • Also this link: http://www.dotnetexpertguide.com/2012/01/dividing-mvc-components-in-separate.html – Steven Nov 01 '12 at 18:35
  • ahh got it. As in the picture i would like to make my wmwebservicetest a actual webservice that contains a reference to WMCommon. Based on the image am I doing anything wrong? – Nick Manojlovic Nov 01 '12 at 18:36
  • Ok, you may hate me for this. But it's been a long day. All the places I said to add a `Service Reference`, it should be `Add Reference` ONLY....lol...sorry mate. So, right click on Reference folder, and then choose Add Reference – Steven Nov 01 '12 at 18:41
  • Can any one please see this [question](https://stackoverflow.com/questions/46444678/consuming-web-api-using-httpclient-in-c-sharp-console-application/46445035#46445035) – Moeez Sep 27 '17 at 10:39
0

you can create your own Client Service class that will serve for every request.

 public class ClientService
{
    #region async helper methods

    private static string m_mediaTypeHeaderValue= "application/json";
    static HttpClient client = new HttpClient();
    static HttpClient createHttpClientInstance()
    {          
        return client ?? new HttpClient();
    }

    // SELECT

    internal static async Task<T> Get<T>(string endpoint)
    {
                client= createHttpClientInstance();
               var response = await client.GetAsync(endpoint);
            string content = await response.Content.ReadAsStringAsync();
            return await Task.Run(() => JsonConvert.DeserializeObject<T>(content));
    }
    // INSERT

    static async Task<T> Post<T>(string endpoint, object data)
    {
        client = createHttpClientInstance();
        var httpContent = new StringContent(JsonConvert.SerializeObject(data));
            httpContent.Headers.ContentType = new MediaTypeHeaderValue(m_mediaTypeHeaderValue);
            var response = await client.PostAsync(endpoint, httpContent);
            string content = await response.Content.ReadAsStringAsync();
            return await Task.Run(() => JsonConvert.DeserializeObject<T>(content));
    }

    // UPDATE

    static async Task<T> Put<T>(string endpoint, object data)
    {
        client = createHttpClientInstance();
        var httpContent = new StringContent(JsonConvert.SerializeObject(data));
            httpContent.Headers.ContentType = new MediaTypeHeaderValue(m_mediaTypeHeaderValue);

            var response = await client.PutAsync(endpoint, httpContent);
            string content = await response.Content.ReadAsStringAsync();
            return await Task.Run(() => JsonConvert.DeserializeObject<T>(content));
    }

    // DELETE

    static async Task<T> Delete<T>(string endpoint)
    {
    client = createHttpClientInstance();
    var response = await client.DeleteAsync(endpoint);
            string content = await response.Content.ReadAsStringAsync();
            return await Task.Run(() => JsonConvert.DeserializeObject<T>(content));
    }

    #endregion
}
lazydeveloper
  • 891
  • 10
  • 20