5

I have created a new Project, selected ASP.NET Core Web Application (.NET Core), then selected Web Application, Individual User Accounts.

All is good and the project works perfectly, but I want to add WebAPI functionality to this project, so that http://website.com/Home is MVC, and http://website.com/api/whatever is my api, I would like them both to use the same authentication database (so you can register on the MVC site and authenticate to the API).

I do not want to add a second project to the solution if I can avoid it.

Someone posted how to add WebAPI 4 to an existing MVC project but those instructions failed at step 1, add x to the Global.asax, which doesn't exist for an ASP.Net Core MVC Project.

Please help.

1 Answer 1

13

Your ASP.NET Core Controller already supports both MVC and WebAPI. In ASP.NET Core these frameworks were combined together. So all you need is declare a controller action but instead of returning ViewResult return your REST API model.

Example:

public class ValuesController : Controller
{
    [HttpGet]
    public List<string> Get()
    {
        return new List<string> { "Hello", "World" };
    }

    [HttpGet]
    [Route("values/{valueName}")]
    public string Get(string valueName)
    {
        return valueName;
    }
}

It must be accessible under GET: /api/values and GET /api/values/ + valueName, depending on configuration. These are most common use cases.

Good luck.

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

13 Comments

Well I created my class, added a scaffolding item, set the context etc, and then I got this... There was an error creating the DbContext instance to get the model. No parameterless constructor defined for this object.
Or, create controller, API Controller with Actions using Entity Framework, set context, same error.
You were right, just selected the item API Controller with read/write actions, and it did it, thank you :) Answer accepted.
So how do I access my api then? I tried /api/Tests and it offers to download a json file called Tests.json ??
How do you authenticate API requests?
|

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.