加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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

发布时间:2020-12-15 19:06:38 所属栏目:asp.Net 来源:网络整理
导读:对于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 Sec
对于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浏览器不期望这种类型的响应,而是依赖服务器发送重定向响应?

解决方法

重定向post或post / redirect / get后,您的应用程序必须做到用户友好。

编辑。这是超越HTTP规范。如果我们在POST后简单地返回201,浏览器后退按钮的行为就会很糟糕。

请注意,Web服务请求(不响应浏览器)完全遵循标准,并且不会在发布后重定向。

它工作这样。

>浏览器POSTS的数据。
>您的应用程序验证数据。如果它无效,你回复表单,以便他们可以解决它和POST。
>您的应用程序用重定向进行响应。
>浏览器获取重定向并执行GET。
>您的应用程序看到GET并作出响应。

现在 – 嘿presto! – 后退按钮工作。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读