I'm creating a Web Api in .NET Framework that is connected to an ASMX service. No own logic, just pass through data.
Everything works as expected. But not sure if it's good. Have to repeat the same try/catch block in all controller actions.
SecurityController - send username and password and retrieve a session Id to use in subsequent calls:
public class SecurityController : ApiController
{
public SecurityController(ILogger logger)
{
Logger = logger;
}
ILogger Logger { get; }
[HttpPost]
public IHttpActionResult StartSession([FromBody] StartSessionRequestModel requestModel)
{
var client = new SecurityFacade(); // from proxy class
var requestMessage = new StartSessionRequest
{
Username = requestModel.Username,
Password = requestModel.Password
};
try
{
var startSessionResponse = client.StartSession(requestMessage);
return Ok(new
{
startSessionResponse.SessionId
});
}
catch (SoapException ex)
{
return BadRequest(ex.Code.Name);
}
catch (Exception ex)
{
Logger.Error(ex);
return InternalServerError(ex);
}
}
}
Output when entered wrong user/password
{
"Message": "InvalidUsernameAndPasswordPair"
}
On the client (Xamarin), using RestSharp.
var request = new RestRequest("security/startsession");
request.AddParameter("Username", Username);
request.AddParameter("Password", Password);
restClient.PostAsync<StartSessionResponse>(request, (response, handle) =>
{
if (response.IsSuccessful)
{
var sessionId = response.Data.SessionId;
// todo
}
else
{
var responseMessage = JsonConvert.DeserializeAnonymousType(response.Content, new { Message = "" });
if (responseMessage.Message == "InvalidUsernameAndPasswordPair")
{
// todo: show "invalid user/password" error
}
else
{
// todo: show other nicely worded error
}
}
});