Escolar Documentos
Profissional Documentos
Cultura Documentos
o
all
By Steve Smith
Mobile apps can easily communicate with ASP.NET Core backend services.
Features
The ToDoRest app supports listing, adding, deleting, and updating To-Do items. Each item has
an ID, a Name, Notes, and a property indicating whether it's been Done yet.
The main view of the items, as shown above, lists each item's name and indicates if it's done with
a checkmark.
Note
Make sure you run the application directly, rather than behind IIS Express, which ignores non-
local requests by default. Run dotnet run from a command prompt, or choose the application
name profile from the Debug Target dropdown in the Visual Studio toolbar.
Add a model class to represent To-Do items. Mark required fields using the [Required] attribute:
C#Copy
using System.ComponentModel.DataAnnotations;
namespace ToDoApi.Models
{
public class ToDoItem
{
[Required]
public string ID { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Notes { get; set; }
The API methods require some way to work with data. Use the same IToDoRepository interface
the original Xamarin sample uses:
C#Copy
using System.Collections.Generic;
using ToDoApi.Models;
namespace ToDoApi.Interfaces
{
public interface IToDoRepository
{
bool DoesItemExist(string id);
IEnumerable<ToDoItem> All { get; }
ToDoItem Find(string id);
void Insert(ToDoItem item);
void Update(ToDoItem item);
void Delete(string id);
}
}
For this sample, the implementation just uses a private collection of items:
C#Copy
using System.Collections.Generic;
using System.Linq;
using ToDoApi.Interfaces;
using ToDoApi.Models;
namespace ToDoApi.Services
{
public class ToDoRepository : IToDoRepository
{
private List<ToDoItem> _toDoList;
public ToDoRepository()
{
InitializeData();
}
_toDoList.Add(todoItem1);
_toDoList.Add(todoItem2);
_toDoList.Add(todoItem3);
}
}
}
services.AddSingleton<IToDoRepository,ToDoRepository>();
}
The controller requires an IToDoRepository to function; request an instance of this type through
the controller's constructor. At runtime, this instance will be provided using the framework's
support for dependency injection.
C#Copy
using System;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using ToDoApi.Interfaces;
using ToDoApi.Models;
namespace ToDoApi.Controllers
{
[Route("api/[controller]")]
public class ToDoItemsController : Controller
{
private readonly IToDoRepository _toDoRepository;
public ToDoItemsController(IToDoRepository toDoRepository)
{
_toDoRepository = toDoRepository;
}
This API supports four different HTTP verbs to perform CRUD (Create, Read, Update, Delete)
operations on the data source. The simplest of these is the Read operation, which corresponds
to an HTTP GET request.
Reading Items
Requesting a list of items is done with a GET request to the List method.
The [HttpGet] attribute on the List method indicates that this action should only handle GET
requests. The route for this action is the route specified on the controller. You don't necessarily
need to use the action name as part of the route. You just need to ensure each action has a
unique and unambiguous route. Routing attributes can be applied at both the controller and
method levels to build up specific routes.
C#Copy
[HttpGet]
public IActionResult List()
{
return Ok(_toDoRepository.All);
}
The List method returns a 200 OK response code and all of the ToDo items, serialized as JSON.
You can test your new API method using a variety of tools, such as Postman, shown here:
Creating Items
By convention, creating new data items is mapped to the HTTP POST verb. The Create method
has an [HttpPost] attribute applied to it, and accepts a ToDoItem instance. Since
the item argument will be passed in the body of the POST, this parameter is decorated with
the [FromBody] attribute.
Inside the method, the item is checked for validity and prior existence in the data store, and if no
issues occur, it's added using the repository. Checking ModelState.IsValid performs model
validation, and should be done in every API method that accepts user input.
C#Copy
[HttpPost]
public IActionResult Create([FromBody] ToDoItem item)
{
try
{
if (item == null || !ModelState.IsValid)
{
return BadRequest(ErrorCode.TodoItemNameAndNotesRequired.ToString());
}
bool itemExists = _toDoRepository.DoesItemExist(item.ID);
if (itemExists)
{
return StatusCode(StatusCodes.Status409Conflict,
ErrorCode.TodoItemIDInUse.ToString());
}
_toDoRepository.Insert(item);
}
catch (Exception)
{
return BadRequest(ErrorCode.CouldNotCreateItem.ToString());
}
return Ok(item);
}
The sample uses an enum containing error codes that are passed to the mobile client:
C#Copy
[HttpPut]
public IActionResult Edit([FromBody] ToDoItem item)
{
try
{
if (item == null || !ModelState.IsValid)
{
return BadRequest(ErrorCode.TodoItemNameAndNotesRequired.ToString());
}
var existingItem = _toDoRepository.Find(item.ID);
if (existingItem == null)
{
return NotFound(ErrorCode.RecordNotFound.ToString());
}
_toDoRepository.Update(item);
}
catch (Exception)
{
return BadRequest(ErrorCode.CouldNotUpdateItem.ToString());
}
return NoContent();
}
To test with Postman, change the verb to PUT. Specify the updated object data in the Body of
the request.
This method returns a NoContent (204) response when successful, for consistency with the pre-
existing API.
Deleting Items
Deleting records is accomplished by making DELETE requests to the service, and passing the ID
of the item to be deleted. As with updates, requests for items that don't exist will
receive NotFound responses. Otherwise, a successful request will get a NoContent (204) response.
C#Copy
[HttpDelete("{id}")]
public IActionResult Delete(string id)
{
try
{
var item = _toDoRepository.Find(id);
if (item == null)
{
return NotFound(ErrorCode.RecordNotFound.ToString());
}
_toDoRepository.Delete(id);
}
catch (Exception)
{
return BadRequest(ErrorCode.CouldNotDeleteItem.ToString());
}
return NoContent();
}
Note that when testing the delete functionality, nothing is required in the Body of the request.
Common Web API Conventions
As you develop the backend services for your app, you will want to come up with a consistent
set of conventions or policies for handling cross-cutting concerns. For example, in the service
shown above, requests for specific records that weren't found received a NotFound response,
rather than a BadRequest response. Similarly, commands made to this service that passed in
model bound types always checked ModelState.IsValid and returned a BadRequest for invalid
model types.
Once you've identified a common policy for your APIs, you can usually encapsulate it in a filter.
Learn more about how to encapsulate common API policies in ASP.NET Core MVC applications.
Feedback
We'd love to hear your thoughts. Choose the type you'd like to provide:
Product feedback
Sign in to give documentation feedback
Our new feedback system is built on GitHub Issues. Read about this change in our blog post.
0 Open
1 Closed
https://docs.microsoft.com/en-us/aspnet/core/mobile/native-mobile-backend?view=aspnetcore-2.0