我有一个显示所有用户的操作,我还有一个创建用户的操作。创建用户后,我想让我先显示所有用户。
显示所有用户的操作:
...
[HttpGet]
public IEnumerable<User> GetAll()
{
return userRepository.GetAll();
}
...
创建用户的操作:
...
[HttpPost]
public IActionResult Create([FromBody] User user)
{
if(user == null)
return BadRequest();
userRepository.Add(user);
return GetAll(); // were is here i want call the first action
}
...
如何解决?
成功处理表单POST后,网络服务器应将HTTP 303重定向返回到GET操作。 There's a good Wikipedia article about this。
请勿在POST响应中返回正常内容(除非是带有验证错误的表单),因为(出于许多其他原因)用户的浏览器将不允许用户刷新页面而不重新提交表单,并且用户无法直接通过GET请求访问同一页面(这就是为什么现在过时的ASP.NET WebForms的“回发”技术如此糟糕,因此已被终止)。
只需这样做:
return this.RedirectToAction( nameof(this.GetAll) );
但是,RedirectToAction
创建一个HTTP 302重定向,严格来说,这是不正确的,因为您应该返回HTTP 303,这意味着您需要这样做:
public class SeeOtherRedirectResult : ActionResult
{
private readonly string url;
public PermanentRedirectResult(string url)
{
this.url = url;
}
public override void ExecuteResult(ControllerContext context)
{
context.HttpContext.Response.StatusCode = 303;
context.HttpContext.Response.RedirectLocation = this.url;
}
}
// Inside your action:
return new SeeOtherRedirectResult( this.Urls.Action( nameof(this.GetAll) ) );