0

I have an application with a series of webservices with a common token authentication. So each services gets passed in a token and if it's valid then the webservice continues and returns the appropriate type.

[WebMethod]
public List<Student> getStudents(string schoolID, string authToken)
{
    var authenticate = new Authenticate();
    var authorized = authenticate.ValidateAuthorizationToken(authToken);

    if (authorized)
    { 
         // Do something and return a type (in this case a list of Student)
    }
    else
    {
         // return null?          
    }
}

My question is do I just return null if the token is invalid? I could return an error message but I have several different services and some return strings, some return lists, some bool etc. If a list is the return type how do I indicate a invalid token?

mason
  • 31,774
  • 10
  • 77
  • 121
EvilEddie
  • 1,026
  • 2
  • 12
  • 23
  • Why are you using WebMethod? Why not switch to using Web API? If you're set on using WebMethod, why not change the method signature to return something more generic, like an `object`? Or create a class `GetStudentResponse` that contain either a list of students or an error message. – mason Oct 02 '17 at 20:00

1 Answers1

1

If you're deadset on using WebMethod (you really should abandon that and use a modern architecture like Web API) then you can create a class to encapsulate your response.

public class GetStudentsResponse
{
    public bool IsSuccessful { get; set; }

    public string ErrorMessage { get; set; }

    public List<Student> Students { get; set; }
}

[WebMethod]
public GetStudentsResponse getStudents(string schoolID, string authToken)
{
    var response = new GetStudentsResponse();
    var authenticate = new Authenticate();
    var authorized = authenticate.ValidateAuthorizationToken(authToken);

    if (authorized)
    { 
         response.IsSuccessful = true;
         response.Students = GetStudents();
    }
    else
    {
         response.IsSuccessful = false;
         response.ErrorMessage = "Invalid token";       
    }

    return response;
}

On your client side, check the IsSuccessful property. If it's successful, continue as normal. Otherwise, display an error to the user.

You can also set the status code of the Response to 401 but that requires modifying the response directly.

mason
  • 31,774
  • 10
  • 77
  • 121