Shaul Behr
Shaul Behr

Reputation: 38003

How to return an IHttpActionResult inside an MVC Controller?

I'm tinkering with an MVC Controller, having lifted some code out of an ApiController:

public class LoginController : Controller
{
    public async Task<IHttpActionResult> Login(LoginModel model)
    {
        var success = await _accountClient.Login(model);
        if (!success)
        {
            return new UnauthorizedResult(Enumerable.Empty<AuthenticationHeaderValue>(), new HttpRequestMessage());
        }
        return new OkResult(new HttpRequestMessage());
    }
}

This just doesn't look or feel right, particularly the part where I'm creating a new HttpRequestMessage; I'm pretty sure that should somehow come from the incoming Request, but I can't figure out where that's supposed to come from.

Also, how do you create the IEnumerable<AuthenticationHeaderValue> object for the challenges parameter to the UnauthorizedResult constructor?

Upvotes: 0

Views: 2085

Answers (1)

Dandy
Dandy

Reputation: 2177

You can add headers to your Response object as

Response.AddHeader("Token","your-generated-token");

Also you can change your action method as

public async Task<HttpStatusCodeResult> Login(LoginModel model)
{
    var success = await _accountClient.Login(model);
    if (!success)
    {
        return new HttpStatusCodeResult(HttpStatusCode.Unauthorized);
    }
    return new HttpStatusCodeResult(HttpStatusCode.Ok);
}

Upvotes: 1

Related Questions