对于POST方法,W3规范说:
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(第8.5节)
标准响应实际上似乎是向新创建的资源发送重定向。
我使用ASP.NET MVC构建我的网站,并试图遵循规范,所以创建了一个ResourceCreatedResult类:
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); } }
我的行为看起来像这样:
[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; }
但是,IE,Firefox和Chrome都无法重定向到新资源。我弄错了生成正确的响应,或者Web浏览器不期望这种类型的响应,而是依赖服务器发送重定向响应?