I'm learning WebAPI framework for ASP.NET and C#. Is the following way of handling incoming data correct?
[HttpPost]
[ExpiredCookieCheck]
public IHttpActionResult Auth([FromBody]AuthenticationData authenticationData)
{
try
{
if (authenticationData == null)
using (var responseManager = new ResponseManager())
return responseManager.PrepareMessage(
HttpStatusCode.Unauthorized,
"No authentication model was provided in request body.",
null,
ResponseManager.ResponseType.InterfacePlainText
);
using (var authenticationHandler = new AuthenticationHandler())
{
var validationData = authenticationHandler.CheckAuthenticationDataFromWeb(authenticationData);
if (!validationData.Key)
using (var responseManager = new ResponseManager())
return responseManager.PrepareMessage(
HttpStatusCode.Unauthorized,
"Incorrect credentials for authentication.",
null,
ResponseManager.ResponseType.InterfacePlainText
);
using (var cookieManager = new CookieManager())
using (var responseManager = new ResponseManager())
{
var authenticationCookie = cookieManager.CreateAuthenticationCookieHeader(Request.RequestUri.Host);
cookieManager.SaveAuthenticationCookie(validationData.Value.Id, authenticationCookie);
return responseManager.PrepareMessage(
HttpStatusCode.OK,
null,
authenticationCookie,
ResponseManager.ResponseType.InterfacePlainText
);
}
}
}
catch (Exception exception)
{
using (var responseManager = new ResponseManager())
return responseManager.PrepareMessage(
HttpStatusCode.Unauthorized,
exception.ToString(),
null,
ResponseManager.ResponseType.InterfacePlainText
);
}
}
I'm thinking that I'm using something not correctly. I dislike my way of defining using
statements. Maybe it's miles better to define at the beginning of the method all required using
statements and then only call internal methods of objects from those using
statements.
Also, is it correct to use try/catch block of code in Web API controller method? I'm thinking that it could be incorrect to handle some possible errors in Web API method, couldn't it?