asp.net-mvc - 对 HTTP POST 请求的正确响应是什么?

标签 asp.net-mvc http http-headers

对于 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);
    }
}

我的 Action 看起来像这样:

[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 都无法重定向到新资源。我是否搞砸了生成正确的响应,或者网络浏览器不期望这种类型的响应,而是依赖服务器发送重定向响应?

最佳答案

明确地说,浏览器(包括像 Firefox 3 和 IE8 这样的现代浏览器)不会“接受提示”并跟进 HTTP 201: Created 响应,并向中提供的 URI 发出 GET 请求Location header 。

如果您希望浏览器转到 Location header 中提供的 URI,您应该发送 HTTP 303: See Other 状态。

关于asp.net-mvc - 对 HTTP POST 请求的正确响应是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/420103/

相关文章:

android - 在 android 4.1.2 中将数据从 android 设备发送到服务器

Python requests.exception.ConnectionError : connection aborted "BadStatusLine"

php - PHP http 流的正确 header 和 mime_type

asp.net-mvc - Dotnet Cli - 发布命令不更改 Web 配置中的环境变量

asp.net-mvc - MVC 中的底页等价物是什么

.net - System.Web.Razor 与 System.Web.WebPages.Razor

c# - MVC结构查询

c# - 使用 POST 而不是通常的 WSDL 路由来使用 Web 服务

c - 读取期间通过套接字连接超时获取请求

javascript - 谷歌分析内容安全政策