- Visual Studio For Mac
- Using Visual Studio For Mac Asp.net Core Mvc Conference
- Microsoft Visual Studio For Mac
- Using Visual Studio For Mac Asp.net Core Mvc Nj
- Using Visual Studio For Mac Asp.net Core Mvc Interview
- Download Microsoft Visual Studio For Mac
I have Visual Studio 2017 Community Edition installed on my windows machine. I try to create a new project - File -> New Project -> web -> Asp.NET Core Project -> MVC -> Individual user accounts. Project initializes.
By Mike Wasson and Rick Anderson
HTTP is not just for serving up web pages. It’s also a powerful platform for building APIs that expose services and data. HTTP is simple, flexible, and ubiquitous. Almost any platform that you can think of has an HTTP library, so HTTP services can reach a broad range of clients, including browsers, mobile devices, and traditional desktop apps.
In this tutorial, you’ll build a simple web API for managing a list of “to-do” items. You won’t build any UI in this tutorial.
ASP.NET Core has built-in support for MVC building Web APIs. Unifying the two frameworks makes it simpler to build apps that include both UI (HTML) and APIs, because now they share the same code base and pipeline.
Note
If you are porting an existing Web API app to ASP.NET Core, see Migrating from ASP.NET Web API
Sections:
Here is the API that you’ll create:
API | Description | Request body | Response body |
---|---|---|---|
GET /api/todo | Get all to-do items | None | Array of to-do items |
GET /api/todo/{id} | Get an item by ID | None | To-do item |
POST /api/todo | Add a new item | To-do item | To-do item |
PUT /api/todo/{id} | Update an existing item | To-do item | None |
PATCH /api/todo/{id} | Update an existing item | To-do item | None |
DELETE /api/todo/{id} | Delete an item. | None | None |
The following diagram show the basic design of the app.
- The client is whatever consumes the web API (browser, mobile app, and so forth). We aren’t writing a client in this tutorial. We’ll use Postman to test the app.
- A model is an object that represents the data in your application. In this case, the only model is a to-do item. Models are represented as simple C# classes (POCOs).
- A controller is an object that handles HTTP requests and creates the HTTP response. This app will have a single controller.
- To keep the tutorial simple, the app doesn’t use a database. Instead, it just keeps to-do items in memory. But we’ll still include a (trivial) data access layer, to illustrate the separation between the web API and the data layer. For a tutorial that uses a database, see Building your first ASP.NET Core MVC app with Visual Studio.
Start Visual Studio. From the File menu, select New > Project.
Select the ASP.NET Core Web Application (.NET Core) project template. Name the project TodoApi
, clear Host in the cloud, and tap OK.
In the New ASP.NET Core Web Application (.NET Core) - TodoApi dialog, select the Web API template. Tap OK.
A model is an object that represents the data in your application. In this case, the only model is a to-do item.
Add a folder named “Models”. In Solution Explorer, right-click the project. Select Add > New Folder. Name the folder Models.
Note
You can put model classes anywhere in your project, but the Models folder is used by convention.
Add a TodoItem
class. Right-click the Models folder and select Add > Class. Name the class TodoItem
and tap Add.
Replace the generated code with:
A repository is an object that encapsulates the data layer, and contains logic for retrieving data and mapping it to an entity model. Even though the example app doesn’t use a database, it’s useful to see how you can inject a repository into your controllers. Create the repository code in the Models folder.
Start by defining a repository interface named ITodoRepository
. Use the class template (Add New Item > Class).
This interface defines basic CRUD operations.
Next, add a TodoRepository
class that implements ITodoRepository
:
Visual Studio For Mac
Build the app to verify you don’t have any compiler errors.
By defining a repository interface, we can decouple the repository class from the MVC controller that uses it. Instead of instantiating a TodoRepository
inside the controller we will inject an ITodoRepository
using the built-in support in ASP.NET Core for dependency injection.
This approach makes it easier to unit test your controllers. Unit tests should inject a mock or stub version of ITodoRepository
. That way, the test narrowly targets the controller logic and not the data access layer.
In order to inject the repository into the controller, we need to register it with the DI container. Open the Startup.cs file. Add the following using directive:
In the ConfigureServices
method, add the highlighted code:
In Solution Explorer, right-click the Controllers folder. Select Add > New Item. In the Add New Item dialog, select the Web API Controller Class template. Name the class TodoController
.
Replace the generated code with the following:
This defines an empty controller class. In the next sections, we’ll add methods to implement the API.
To get to-do items, add the following methods to the TodoController
class.
These methods implement the two GET methods:
GET/api/todo
GET/api/todo/{id}
Here is an example HTTP response for the GetAll
method:
Later in the tutorial I’ll show how you can view the HTTP response using Postman.
Routing and URL paths¶
The [HttpGet]
attribute (HttpGetAttribute
) specifies an HTTP GET method. The URL path for each method is constructed as follows:
- Take the template string in the controller’s route attribute,
[Route('api/[controller]')]
- Replace “[Controller]” with the name of the controller, which is the controller class name minus the “Controller” suffix. For this sample, the controller class name is TodoController and the root name is “todo”. ASP.NET Core routing is not case sensitive.
- If the
[HttpGet]
attribute has a template string, append that to the path. This sample doesn’t use a template string.
In the GetById
method:
'{id}'
is a placeholder variable for the ID of the todo
item. When GetById
is invoked, it assigns the value of “{id}” in the URL to the method’s id
parameter.
Name='GetTodo'
creates a named route and allows you to link to this route in an HTTP Response. I’ll explain it with an example later.
Return values¶
The GetAll
method returns an IEnumerable
. MVC automatically serializes the object to JSON and writes the JSON into the body of the response message. The response code for this method is 200, assuming there are no unhandled exceptions. (Unhandled exceptions are translated into 5xx errors.)
In contrast, the GetById
method returns the more general IActionResult
type, which represents a wide range of return types. GetById
has two different return types:
- If no item matches the requested ID, the method returns a 404 error. This is done by returning
NotFound
. - Otherwise, the method returns 200 with a JSON response body. This is done by returning an
ObjectResult
Launch the app¶
In Visual Studio, press CTRL+F5 to launch the app. Visual Studio launches a browser and navigates to http://localhost:port/api/values
, where port is a randomly chosen port number. If you’re using Chrome, Edge or Firefox, the data will be displayed. If you’re using IE, IE will prompt to you open or save the values.json file.
We’ll add Create
, Update
, and Delete
methods to the controller. These are variations on a theme, so I’ll just show the code and highlight the main differences. Build the project after adding or changing code.
Create¶
This is an HTTP POST method, indicated by the [HttpPost] attribute. The [FromBody] attribute tells MVC to get the value of the to-do item from the body of the HTTP request.
The CreatedAtRoute method returns a 201 response, which is the standard response for an HTTP POST method that creates a new resource on the server. CreateAtRoute
also adds a Location header to the response. The Location header specifies the URI of the newly created to-do item. See 10.2.2 201 Created.
Use Postman to send a Create request¶
- Set the HTTP method to
POST
- Tap the Body radio button
- Tap the raw radio button
- Set the type to JSON
- In the key-value editor, enter a Todo item such as
{'Name':'<yourto-doitem>'}
- Tap Send
Tap the Headers tab and copy the Location header:
Using Visual Studio For Mac Asp.net Core Mvc Conference
You can use the Location header URI to access the resource you just created. Recall the GetById
method created the 'GetTodo'
named route:
Update¶
Update
is similar to Create
, but uses HTTP PUT. The response is 204 (No Content).According to the HTTP spec, a PUT request requires the client to send the entire updated entity, not just the deltas. To support partial updates, use HTTP PATCH.
Update with Patch¶
This overload is similar to the previously shown Update
, but uses HTTP PATCH. The response is 204 (No Content).
Delete¶
Microsoft Visual Studio For Mac
The response is 204 (No Content).
- To learn about creating a backend for a native mobile app, see 🔧 Creating Backend Services for Native Mobile Applications.
- For information about deploying your API, see Publishing and Deployment.
I realize this is a bit insane, C# being a Windows language and all, but I want to start learning C# mostly because I'm interested in ASP.NET MVC. I work as a web developer by day and my office is completely run on *nix machines. The developers and all other staff use Mac OS X and our servers are all some variation of Linux.
To be honest I just want to try something different than PHP, Python, or Ruby. The catch is that I don't want to give up my beloved Mac OS X. I've looked at Mono a bit and it seems like exactly what I am looking for. Unfortunately MonoDevelop is very slow to the point of uselessness on Mac OS X. (Unless I'm doing something wrong which is entirely plausible).
So my question boils down to this: What is the best way to code and compile C# apps on Mac OS X. (Running the code is not that big of issue, I'll probably just get some cheap server space to run my ASP.NET MVC apps on. I'm not really looking to run any apps on Mac OS X.)
macinjoshmacinjosh8 Answers
In my own experience as a C#/Windows/ASP.Net developer the greatest strength of the platform is the integration with the tools. That said it is difficult to get it all running on mono. Mono would be an excellent deployment platform. But if you want to learn asp.net MVC your best bet is to set up a virtual Windows environment and get the free visual web developer visual studio: http://www.microsoft.com/express/vwd/ .
The other reason is that if you're trying to learn the platform, most resources will use some variant of Visual Studio. I find it rather difficult to try and learn a framework and have to struggle with platform differences at the same time.
I say this as an avid OS X user that has done C# development for several years and has done several small projects in asp.net mvc.
MinMinwhat about running a virtual Windows machine on your Mac?
see http://www.parallels.com/eu/products/desktop/
jaojao+1 to Min's answer.
The tools Microsoft provides (free and purchased) are amazing and integrate very well. The more I use Visual Studio, the more I love it.
I highly suggest doing your dev for ASP.NET/C# on Windows (bootcamp or vmware or w/e).
Having to switch between OSes when you want to code is a small price to pay compared to the potential compatibility headaches you might face in the future.
I'd add to the virtualisation argument. If you were to go for a Windows installation in VMWare Fusion, for example, you can run it in coherence mode. In this mode, you still get all the apps and system you know and love in OS X, and make Visual Studio appear as if tit were a native OS X app. VS, though, 'sees' the Windows environment, so you get the benfits of developing on Windows.
Of course, you have the overhead of having two OSs competing for resources, but most of the time this is not an issue (It isn't to me, anyway, and I run my own projects at home this way on a humble MacBook)
Using Visual Studio For Mac Asp.net Core Mvc Nj
ZombieSheepZombieSheepIn case anyone ends up on this question, ASP.NET Core is now out and runs on the Mac. MS has a walkthru detailing creating a Web API with ASP.NET Core: https://docs.microsoft.com/en-us/aspnet/core/tutorials/web-api-vsc
user783836user783836I concur with a virtual windows machine and VS Express, but Mono Develop is not that bad when especially targeting ASP.NET MVC.
kennykennyDeveloping in .net is quite highly IDE-oriented. Of course you can do it all in a plain old text editor but it gets harder and harder unless you're writing back-end server code only. Maybe there are great mono-based IDEs but I can't see why you'd prefer to use MacOS when all the time will be spent using the IDE anyway.
Definitely vote for virtualized Windows or using BootCamp.
Using Visual Studio For Mac Asp.net Core Mvc Interview
Mr. BoyMr. BoyYou could install a linux desktop on your mac (KDE) and use wine(a linux windows emulator app) to install Visual studio express. The KDE desktop runs on a mac. Now you do not have to install a complete windows os on your machine.