I'm currently in the process of developing an application using Asp.net Web API and AngularJS.
While attempting to retrieve data from the API, I encountered a null error.
Asp.net Web API Code
[RoutePrefix("api/user")]
public class UserController : ApiController
{
[Route("login")]
[HttpGet]
public HttpResponseMessage Login(string userId, string password)
{
// code to fetch data
return Request.CreateResponse(HttpStatusCode.OK, result);
}
}
Web Config
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var formatters = GlobalConfiguration.Configuration.Formatters;
formatters.Remove(formatters.XmlFormatter);
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
}
AngularJS Code
this.get = function(url, headers = {}) {
// creating a defer
var def = $q.defer();
$http({
url: url,
dataType: 'json',
method: 'GET',
data: '',
headers: headers
}).success(function(data) {
def.resolve(data);
}).error(function(error) {
def.reject(error);
});
return def.promise;
};
Result
When attempting to get
the data by accessing the API URL, I encountered a null
error.
If I open the URL in a web browser, it returns JSON data.
Network Log
{
"log": {
// Network log details
}
}
Successful Response in Browser