0

I have a Visual Studio 2015 solution that contains an ASP.NET Core Web API along with an ASP.NET Core MVC application.

I intend to use the API in the MVC application, and they are both running at the same time.

For instance, the API is running on localhost:60170 and I have a controller routed to "api/[controller]" as follows:

namespace JobManager.WAPI.Controllers
{
    [Route("api/[controller]")]
    public class ValuesController : Controller
    {

Now, how do I get the routes in my MVC application to the API, without hardcoding the path to the API, i.e. localhost:60170 ?

6
  • You could use Hyprlinkr. Commented Mar 1, 2017 at 19:24
  • There is no such thing as ASP.NET Core Web Api. MVC and Web Api have merged in Core. Commented Mar 1, 2017 at 19:26
  • @NightOwl888: Don't think that will work here. The problem seems to be that the user has created two separate projects, and now wants to share routes between them. Commented Mar 1, 2017 at 19:28
  • @ChrisPratt yes that's it! Commented Mar 1, 2017 at 19:30
  • 1
    @manatttta: You can't share routes between projects. If your website and api are hosted as separate applications, then hardcoding the API paths is unavoidable. You can mitigate some of the damage by using something like Application Settings to store the URLs for the endpoints you need, as then you'd only have to hardcode it in one place, but it will have to be hardcoded. Commented Mar 1, 2017 at 19:31

1 Answer 1

1

Your controller can have both the API methods and MVC methods 'hand-in-hand'.

You can first define your default MVC route in Startup.cs:

        // mvc
        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });

in the controller class, remove the controller attribute [Route("api/[controller]")], instead, use it to decorate the specific API method inside the controller class, for example:

[Route("api/[controller]/XYZ/{..}")]

public IActionResult ABC(..){

}

For MVC methods, just use them as normal:

[HttpGet]

public async Task<IActionResult> Index(..){

}

Don't hard code the localhost address.

Sign up to request clarification or add additional context in comments.

2 Comments

I don't think I understood. How can it access the API methods without me referring to the API port, at least?
sorry, i misunderstood the intent. my solution allows you to have one project to handle both API service and MVC web front end part.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.