Reputation: 784
I'm writing an application that serves both Web API and a MVC content in .NET Core. From the MVC Controller I want to call the API's functions and receive the data that comes back. Is there a better way than using HttpClient
or similar things? Like instantiating the API's controller class in the MVC Controller? I can't just go new ApiController();
since it's depending on dependency injection, can I?
Upvotes: 3
Views: 3220
Reputation: 71
Let us take customer which consists of username and password as a field. First the database is connected with the application using ADO.NET or entity framework and then the for sample application I have written sample post API Method for the customer class(username, password).It return status code 201 when it successfully posted in the database.
public HttpResponseMessage Post([FromBody] Customer cust)
{
try
{
using (CustomerDBEntities entities = new CustomerDBEntities())
{
entities.customer.Add(cust);
entities.SaveChanges();
var message = Request.CreateResponse(HttpStatusCode.Created, cust);
return message;
}
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
}
}
Then After testing the API, we can consume in any platform like MVC, Angular and some other platforms. For Example In MVC, this should be called via API call(URL) and consume it in MVC Controller for the Front end. In the View we can create our UI based on requirements. The sample format for consuming API from MVC Controller is given.
public class Temp_Global
{
public static HttpClient Client = new HttpClient();
static Temp_Global()
{
Client.BaseAddress = new Uri("Mention your API Url");
Client.DefaultRequestHeaders.Clear();
Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
}
public class MVCController
{
public ActionResult AddCustomer(Customer c1)
{
HttpResponseMessage response =
Temp_Global.Client.PostAsJsonAsync("APIControllerName", c1).Result;
TempData["SuccessMessage"] = "Saved Successfully";
return RedirectToAction("Index");
}
}
Upvotes: 0
Reputation: 61859
"Like instantiating the API's controller class in the MVC Controller?"
No, that's not a good idea, and wouldn't really work anyway. You could make a HTTP request as you mentioned, but it's not that efficient if everything is already part of the application.
But if the functionality which actually gets the data is in a separate class, you could call the relevant method of that class and get the data directly - probably better to get it as a variable than as JSON anyway.
This all about your application design - the process of retrieving the data (e.g. from a database) should be functionally separate from the process of providing it to the user (e.g. as JSON via an API controller). So any code should be able to call the data retrieval functionality, not just the API.
Conceptually you might like to think of these as different layers of functionality. It's a common architectural model in software - a presentation layer, (optionally) a logic layer and a data layer.
Upvotes: 4
Reputation: 13060
If your application has both ASP.Net MVC and Web API parts then best solution would be to put any functionality/business logic required to get any data in a service layer. Then both MVC and Web API can consume these directly rather than having to fire up a HttpClient (or similar).
To be honest, this is a good practice anyway whether you have both MVC and Web API, or just one. This would allow different API/MVC controllers to access the same data in the application without having to duplicate code.
Take a look at Onion Architecture which typically has 4 layers.
There's a good article over on C# Corner that explains Onion Architecture.
Upvotes: 4