- Sending HTML Form Data in ASP.NET Web API: Form-urlencoded Data
- Overview of HTML Forms
- Sending Complex Types
- Sending Form Data via AJAX
- Sending Simple Types
- POST
- Синтаксис
- Пример
- Спецификация
- Совместимость с браузерами
- Смотрите также
- Found a content problem with this page?
- Posting HTML Form to the Server
- What is HTTP POST?
- What is HTML Form?
- Submitting HTML Forms over HTTP
- Submitting HTML Forms in JSON Format
- Submitting HTML Forms using the HTTP GET Method
- See also
- Generate Code Snippets for POST HTML Form Example
Sending HTML Form Data in ASP.NET Web API: Form-urlencoded Data
This article shows how to post form-urlencoded data to a Web API controller.
Overview of HTML Forms
HTML forms use either GET or POST to send data to the server. The method attribute of the form element gives the HTTP method:
The default method is GET. If the form uses GET, the form data is encoded in the URI as a query string. If the form uses POST, the form data is placed in the request body. For POSTed data, the enctype attribute specifies the format of the request body:
enctype | Description |
---|---|
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. |
Part 1 of this article looks at x-www-form-urlencoded format. Part 2 describes multipart MIME.
Sending Complex Types
Typically, you will send a complex type, composed of values taken from several form controls. Consider the following model that represents a status update:
namespace FormEncode.Models < using System; using System.ComponentModel.DataAnnotations; public class Update < [Required] [MaxLength(140)] public string Status < get; set; >public DateTime Date < get; set; >> >
Here is a Web API controller that accepts an Update object via POST.
namespace FormEncode.Controllers < using FormEncode.Models; using System; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Web; using System.Web.Http; public class UpdatesController : ApiController < static readonly Dictionaryupdates = new Dictionary(); [HttpPost] [ActionName("Complex")] public HttpResponseMessage PostComplex(Update update) < if (ModelState.IsValid && update != null) < // Convert any HTML markup in the status text. update.Status = HttpUtility.HtmlEncode(update.Status); // Assign a new ID. var updates[id] = update; // Create a 201 response. var response = new HttpResponseMessage(HttpStatusCode.Created) < Content = new StringContent(update.Status) >; response.Headers.Location = new Uri(Url.Link("DefaultApi", new < action = "status", >)); return response; > else < return Request.CreateResponse(HttpStatusCode.BadRequest); >> [HttpGet] public Update Status(Guid id) < Update update; if (updates.TryGetValue(id, out update)) < return update; >else < throw new HttpResponseException(HttpStatusCode.NotFound); >> > >
This controller uses action-based routing, so the route template is «api///». The client will post the data to «/api/updates/complex».
Now let’s write an HTML form for users to submit a status update.
Complex Type
Notice that the action attribute on the form is the URI of our controller action. Here is the form with some values entered in:
When the user clicks Submit, the browser sends an HTTP request similar to the following:
POST http://localhost:38899/api/updates/complex HTTP/1.1 Accept: text/html, application/xhtml+xml, */* User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0) Content-Type: application/x-www-form-urlencoded Content-Length: 47 status=Shopping+at+the+mall.&date=6%2F15%2F2012
Notice that the request body contains the form data, formatted as name/value pairs. Web API automatically converts the name/value pairs into an instance of the Update class.
Sending Form Data via AJAX
When a user submits a form, the browser navigates away from the current page and renders the body of the response message. That’s OK when the response is an HTML page. With a web API, however, the response body is usually either empty or contains structured data, such as JSON. In that case, it makes more sense to send the form data using an AJAX request, so that the page can process the response.
The following code shows how to post form data using jQuery.
The jQuery submit function replaces the form action with a new function. This overrides the default behavior of the Submit button. The serialize function serializes the form data into name/value pairs. To send the form data to the server, call $.post() .
When the request completes, the .success() or .error() handler displays an appropriate message to the user.
Sending Simple Types
In the previous sections, we sent a complex type, which Web API deserialized to an instance of a model class. You can also send simple types, such as a string.
Before sending a simple type, consider wrapping the value in a complex type instead. This gives you the benefits of model validation on the server side, and makes it easier to extend your model if needed.
The basic steps to send a simple type are the same, but there are two subtle differences. First, in the controller, you must decorate the parameter name with the FromBody attribute.
[HttpPost] [ActionName("Simple")] public HttpResponseMessage PostSimple([FromBody] string value) < if (value != null) < Update update = new Update() < Status = HttpUtility.HtmlEncode(value), Date = DateTime.UtcNow >; var updates[id] = update; var response = new HttpResponseMessage(HttpStatusCode.Created) < Content = new StringContent(update.Status) >; response.Headers.Location = new Uri(Url.Link("DefaultApi", new < action = "status", >)); return response; > else
By default, Web API tries to get simple types from the request URI. The FromBody attribute tells Web API to read the value from the request body.
Web API reads the response body at most once, so only one parameter of an action can come from the request body. If you need to get multiple values from the request body, define a complex type.
Second, the client needs to send the value with the following format:
Specifically, the name portion of the name/value pair must be empty for a simple type. Not all browsers support this for HTML forms, but you create this format in script as follows:
And here is the script to submit the form value. The only difference from the previous script is the argument passed into the post function.
$('#form2').submit(function () < var jqxhr = $.post('api/updates/simple', < "": $('#status1').val() >) .success(function () < var loc = jqxhr.getResponseHeader('Location'); var a = $('', < href: loc, text: loc >); $('#message').html(a); >) .error(function () < $('#message').html("Error posting the update."); >); return false; >);
You can use the same approach to send an array of simple types:
POST
HTTP-метод POST предназначен для отправки данных на сервер. Тип тела запроса указывается в заголовке Content-Type .
Разница между PUT и POST состоит в том, что PUT является идемпотентным: повторное его применение даёт тот же результат, что и при первом применении (то есть у метода нет побочных эффектов), тогда как повторный вызов одного и того же метода POST может иметь такие эффекты, как например, оформление одного и того же заказа несколько раз.
Запрос POST обычно отправляется через форму HTML и приводит к изменению на сервере. element or the formenctype attribute of the or elements:»>В этом случае тип содержимого выбирается путём размещения соответствующей строки в атрибуте enctype элемента или formenctype атрибута элементов или :
- application/x-www-form-urlencoded : значения кодируются в кортежах с ключом, разделённых символом ‘&’ , с ‘=’ между ключом и значением. Не буквенно-цифровые символы — percent encoded: это причина, по которой этот тип не подходит для использования с двоичными данными (вместо этого используйте multipart/form-data )
- multipart/form-data : каждое значение посылается как блок данных («body part»), с заданными пользовательским клиентом разделителем («boundary»), разделяющим каждую часть. Эти ключи даются в заголовки Content-Disposition каждой части
- text/plain
Когда запрос POST отправляется с помощью метода, отличного от HTML-формы, — например, через XMLHttpRequest — тело может принимать любой тип. Как описано в спецификации HTTP 1.1, POST предназначен для обеспечения единообразного метода для покрытия следующих функций:
- Аннотация существующих ресурсов
- Публикация сообщения на доске объявлений, в новостной группе, в списке рассылки или в аналогичной группе статей;
- Добавление нового пользователя посредством модальности регистрации;
- Предоставление блока данных, например, результата отправки формы, процессу обработки данных;
- Расширение базы данных с помощью операции добавления.
Синтаксис
Пример
Простая форма запроса, используя стандартный application/x-www-form-urlencoded content type:
POST /test.html HTTP/1.1 Host: example.org Content-Type: multipart/form-data;boundary="boundary" --boundary Content-Disposition: form-data; name="field1" value1 --boundary Content-Disposition: form-data; name="field2"; filename="example.txt" value2 --boundary--
Спецификация
Совместимость с браузерами
BCD tables only load in the browser
Смотрите также
Found a content problem with this page?
This page was last modified on 21 июн. 2023 г. by MDN contributors.
Your blueprint for a better internet.
Posting HTML Form to the Server
To post HTML form data to the server in URL-encoded format, you need to make an HTTP POST request to the server and provide the HTML form data in the body of the POST message in key=value format. You must also specify the data type using the Content-Type: application/x-www-form-urlencoded request HTTP header. You can also send HTML form data to the server using the HTTP GET method. To do this, HTML form data is passed in the URL as key=value pairs separated by ampersands (&), and keys are separated from values by equality (=). In this HTML Form POST Example, we post the form data to the ReqBin echo URL in the application/x-www-form-urlencoded format. Click Send to run the HTML Form POST example online and see the results.
POST /echo/post/form HTTP/1.1 Host: reqbin.com Content-Type: application/x-www-form-urlencoded Content-Length: 23 key1=value1&key2=value2
What is HTTP POST?
HTTP POST is one of the nine standard methods of the Hypertext Transfer Protocol. The POST method is used to post data to the server, upload files and images, and submit HTML forms. The HTTP POST method differs from HTTP GET and HEAD requests in that POST requests can change the server’s state.
What is HTML Form?
A form is a section of an HTML document that contains controls such as text and password input fields, radio buttons, checkboxes, and a Submit button, enclosed in an HTML
Submitting HTML Forms over HTTP
- Submitting HTML forms using the application/x-www-form-urlencoded media type.
The application/x-www-form-urlencoded media type is mainly used for submitting short HTML forms as key-value pairs, for example, when authorizing a user using login/password forms.
POST /login HTTP/1.1 Host: reqbin.com Content-Type: application/x-www-form-urlencoded Content-Length: 36 login=my_login&password=my_password
POST /upload HTTP/1.1 Host: reqbin.com Content-Type: multipart/form-data Content-Length: 526 =======MIME boundary string Content-Disposition: form-data; login="login", my_login =======MIME boundary string Content-Disposition: form-data; name="file"; filename="image1.jpg" Content-Type: image/jpeg [image data] =======MIME boundary string Content-Disposition: form-data; name="file"; filename="image2.jpg" Content-Type: image/jpeg [image data] =======boundary string--
Submitting HTML Forms in JSON Format
HTML does not have native methods for converting forms to JSON objects. If you want to convert form data to JSON, you need to use JavaScript to:
- Collect form data from a DOM object into a JavaScript object. If you are using jQuery, you can convert your HTML form into a JavaScript object with a single line using the $(«#form»).serializeArray() jQuery method.
- Convert the JavaScript object to JSON string using JSON.stringify() method.
- Send the form data to the server using the XMLHttpRequest or fetch methods.
Submitting HTML Forms using the HTTP GET Method
In some cases, you can submit form data using the HTTP GET method. The form data is passed to the server as a series of name/value URL parameters, and you are limited to the maximum length of the URL. For browsers, the limit is around 2000 characters (browser dependent) for the code, there is no such limit, but your server may have its limitations. For example, the maximum length of an Apache URL is 8177 characters. Submitting HTML forms using the HTTP GET method is less secure because you pass URL parameters data.
GET /login?login=my_login&password=my_passowrd HTTP/1.1 Host: reqbin.com
See also
Generate Code Snippets for POST HTML Form Example
Convert your POST HTML Form request to the PHP, JavaScript/AJAX, Node.js, Curl/Bash, Python, Java, C#/.NET code snippets using the ReqBin code generator.