For a POST method, the W3 specs say:
If a resource has been created on the origin server, the response SHOULD be 201 (Created) and contain an entity which describes the status of the request and refers to the new resource, and a Location header (see Section 10.4).
http://www.ietf.org/internet-drafts/draft-ietf-httpbis-p2-semantics-05.txt (section 8.5)
The standard response actually seems to be to send a Redirect to the newly created resource.
I’m building my site with ASP.NET MVC, and tried to follow the spec, so created a ResourceCreatedResult class:
public class ResourceCreatedResult : ActionResult { public string Location { get; set; } public override void ExecuteResult(ControllerContext context) { context.HttpContext.Response.Clear(); context.HttpContext.Response.StatusCode = 201; context.HttpContext.Response.ClearHeaders(); context.HttpContext.Response.AddHeader('Location', Location); } }
And my action looks something like this:
[AcceptVerbs(HttpVerbs.Post)] public ActionResult CreateNew(string entityStuff) { Entity newEntity = new Entity(entityStuff); IEntityRepository entityRepository = ObjectFactory.GetInstance<IEntityRepository>(); entityRepository.Add(newEntity); ActionResult result = new ResourceCreatedResult() { Location = Url.Action('Show', new { id = newEntity.Id }) }; return result; }
However, IE, Firefox and Chrome all fail to redirect to the new resource. Have I messed up generating the correct response, or do web browsers not expect this type of response, instead relying on servers to send a Redirect response?
Redirect after post or post/redirect/get is something your application must do to be user friendly.
Edit. This is above and beyond the HTTP specifications. If we simply return a 201 after a POST, the browser back button behaves badly.
Note that Web Services requests (which do NOT respond to a browser) follow the standard completely and do NOT redirect after post.
It works like this.
The browser POSTS the data.
Your application validates the data. If it’s invalid, you respond with the form so they can fix it and POST.
Your application responds with a redirect.
The browser gets the redirect and does a GET.
Your application sees the GET and responds.
Now — hey presto! — the back button works.