- Visual Studio 2012
- Apache License, Version 2.0
- ASP.NET
- ASP.NET Web API
- 09/21/2012
Sample code for the tutorial at http://www.asp.net/web-api/overview/working-with-http/sending-html-form-data,-part-1
[Excerpt]
This article shows how to post form-urlencoded data to a Web API controller.
Forms use either GET or POST to send data to the server. The method attribute of the form element gives the HTTP method:
<form action="api/values" method="get">
The default method is GET. Using GET, the form data is encoded in the URI as a query string. Using POST, the form data is placed in the request body, and the enctype attribute specifies the format.
- application/x-www-form-urlencoded: Form data is encoded as name/value pairs, similar to a URI query string. This is the default format for POST.
- multipart/form-data: Form data is encoded as a multipart MIME message. Use this format if you are uploading a file to the server.
This article looks at POST with application/x-www-form-urlencoded encoding.
Typically, you will send a complex type, composed of values from several form controls. Consider the following model:
namespace FormEncode.Models { using System; using System.ComponentModel.DataAnnotations;public class Update { [Required] [MaxLength(140)] public string Status { get; set; } [Required] public DateTime Date { get; set; } }
}
The Update
class represents a status update. Here is a Web API controller that accepts an
Update
object via POST.
namespace FormEncode.Controllers { using System; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Web.Http; using FormEncode.Models;public class UpdatesController : ApiController { static readonly Dictionary<Guid, Update> updates = new Dictionary<Guid,Update>(); [HttpPost] [ActionName("Complex")] public HttpResponseMessage PostComplex(Update update) { if (ModelState.IsValid) { var id = Guid.NewGuid(); updates[id] = update; return ResponseFromPost(update, id); } else { return Request.CreateResponse(HttpStatusCode.BadRequest); } } [HttpGet] public Update Status(Guid id) { Update update; if (updates.TryGetValue(id, out update)) { return update; } else { var resp = Request.CreateResponse(HttpStatusCode.NotFound); throw new HttpResponseException(resp); } } // Create a 201 response for a POST action. private HttpResponseMessage ResponseFromPost(Update update, Guid id) { var resp = new HttpResponseMessage(HttpStatusCode.Created); resp.Content = new StringContent(update.Status); resp.Headers.Location = new Uri(Url.Link("DefaultApi", new { action = "status", id = id })); return resp; } }
}