Reputation: 516
I have some code (see below for details) that uses HttpClient.PostAsync to call a WebApi method on a controller hosted via Owin. The call reaches the proper method on the proper controller and works as expected until I inspect the StatusCode of the HttpResponse object. In my server side code, I either return Ok() or BadRequest() in the event of an exception. However, whether Ok() or BadRequest() is called, the StatusCode is always NoContent (204). How can I fix it so that the StatusCode is either OK (200) or BadRequest (400) as expected?
Client side code:
public async Task<bool> RegisterUser(string server, string userName, string password)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(server);
var response = await client.PostAsync($"/authentication/user/register?userName={HttpUtility.UrlEncode(userName)}&password={HttpUtility.UrlEncode(password)}", new StringContent(string.Empty));
return response.StatusCode == HttpStatusCode.OK;
}
}
Server side code:
public void Register(string userName, string password)
{
try
{
_securityService.RegisterUser(userName, password);
}
catch (Exception e)
{
BadRequest();
return;
}
Ok();
}
Owin configuration code:
var config = new HttpConfiguration();
config.Routes.MapHttpRoute("AuthenticationApi", "authentication/{controller}/{action}");
config.DependencyResolver = lifetimeScope.Resolve<IDependencyResolver>();
app.UseWebApi(config);
Upvotes: 0
Views: 716
Reputation: 236218
You forgot to return anything from your api method - it simply returns void
now. Thus you get No Content
for any request. Yes, you call helper methods which create different action results (BadRequest and Ok) but those action results are not returned from controller method and thus not used by WebApi infrastructure to build a response message.
So you should make your method return appropriate action results:
public IHttpActionResult Register(string userName, string password)
{
try
{
_securityService.RegisterUser(userName, password);
}
catch (Exception e)
{
return BadRequest();
}
return Ok();
}
Note that returning BadRequest
for any exception is a really bad practice. Not every exception is a client fault.
Upvotes: 2