0

My current action looks like this:

[HttpPost]
public void AddMessage([FromBody] ShoutboxMessage input)
{
    if (!string.IsNullOrWhiteSpace(input.Message) && Request.Cookies["usrid"] != null)
    {
        input.SbUserId = int.Parse(Request.Cookies["usrid"]);
        input.Timestamp = DateTime.UtcNow;
        context.ShoutboxMessages.Add(input);
        context.SaveChanges();
    }
}

I would like to just do this:

[HttpPost]
public void AddMessage([FromBody] ShoutboxMessage input)
{
    if (Request.Cookies["usrid"] == null)
        RedirectToAction("Login");

    if (!string.IsNullOrWhiteSpace(input.Message))
    {
        //...
    }
}

but that doesn't work, obviously. Is there a way to redirect from an action that's supposed to return void? Or, the other way around, can an Action that's supposed to return an ActionResult not result in any redirection or reload of the current page?

Edit: the "duplicate" has nothing to do with this. it may be that a void action returns basically the same as an EmptyResult action, but that's not the topic here, basically I want to know how to chose between an EmptyResult and an ActionResult at runtime.

lenny
  • 734
  • 2
  • 15
  • 43
  • Possible duplicate of [ASP.Net MVC Controller Actions that return void](https://stackoverflow.com/questions/2048643/asp-net-mvc-controller-actions-that-return-void) – mjwills Aug 15 '18 at 13:11
  • `EmptyResult` is preferable to `void `. – mjwills Aug 15 '18 at 21:11

1 Answers1

1

Something like this? You can always return EmptyResult() from Action.

[HttpPost]
public ActionResult AddMessage([FromBody] ShoutboxMessage input)
{
    if (Request.Cookies["usrid"] == null)
        return this.RedirectToAction("Login");

    if (!string.IsNullOrWhiteSpace(input.Message))
    {
        //...
        return new EmptyResult();
    }
}
Kamil Folwarczny
  • 581
  • 1
  • 3
  • 13
  • I can't just return null since it will result in a 500 response (even when setting `Response.StatusCode` to 200) and mess up my JS response handling – lenny Aug 15 '18 at 13:29
  • 1
    Strange, i have edited my answer based on link that mjwills posted in comment. In my test project i am receiving regular empty 200 response. – Kamil Folwarczny Aug 15 '18 at 14:32