angular post request to a asp.net web API server - angularjs

IN angular js i am trying to send a post request her is the controller.
.controller('ActivationController',['$http','$location','$routeParams','AuthService',
function($http, $location, $routeParams, AuthService){
var location = $location.path();
var activation_code = $routeParams.code;
var activationLink = "http://localhost:18678/api/User/ActivateUser";
console.log(activation_code);
if(activation_code){
$http({method:"post", url:activationLink, data:activation_code}).success(function(response){
console.log(response);
}).error(function(error){
console.log(error);
});
}
}]);
and in asp.net web API her is the method.
[HttpPost]
public HttpResponseMessage ActivateUser([FromBody]string activation_code)
{
if (!string.IsNullOrWhiteSpace(activation_code))
{
string decode_token = HttpUtility.UrlDecode(activation_code); ;
string token_string = Crypto.Decrypt(activation_code, passPhrase);
if (token_string != null)
{
User activateAcc = db.Users.Where(user => user.ConfirmToken == token_string).SingleOrDefault();
if (activateAcc != null)
{
activateAcc.IsActive = true;
try
{
db.SaveChanges();
var credential = new UserCredential();
credential.EmailAddress = activateAcc.UserMail;
credential.Password = activateAcc.UserPassword;
return Request.CreateResponse(HttpStatusCode.OK, credential);
}
catch
{
return Request.CreateResponse(HttpStatusCode.Ambiguous, "cannot confirm account");
}
}
else
{
return Request.CreateResponse(HttpStatusCode.NotAcceptable, "invalid account");
}
}
else
{
return Request.CreateResponse(HttpStatusCode.NoContent, "invalid token data");
}
}
else
{
return Request.CreateResponse(HttpStatusCode.NoContent, "missing activation code");
}
}
The problem is when the controller fire the request is made but without sending any data to the server. The [FromBody]string activation_codeis null

Wrap your parameter in quotes:
$http({method:"post", url:activationLink, data: '"' + activation_code + '"'});
Explanation
For Web API to bind to a simple string primitive, the body must be specified as:
"some string here"
For example:
POST http://localhost:5076/api/values HTTP/1.1
User-Agent: Fiddler
Host: localhost:5076
Content-Type: application/json
Content-Length: 7
"Alice"
The quotes are important. For more information, check this article.

Related

Angularjs $http get not working

I am trying to access REST web service from angularjs. I am not able to call it successfully.
AngularJs Code
var singleOrderUrl = "/singleOrder/retrieve";
function getSingleOrderDetails(userName,singleOrderUrl,$http,$q) {
var fd = new FormData();
var deffered = $q.defer();
fd.append('USERNAME', 'test123');
//fd.append();
//fd.append();
console.log("inside service"+userName+"singleOrderUrl:::"+singleOrderUrl);
return $http.get(singleOrderUrl, fd, {
withCredentials : false,
transformRequest : angular.identity,
headers : {
'Content-Type' : undefined,
}
}).success(function(response) {
console.log(response);
responseData = response.data.toString();;
deffered.resolve(response);
return responseData;
}).error(function(error) {
alert("error");
deffered.reject(error);
return "failed";
});
};
Rest Service code
#RestController
public class SingleOrderHistoryController {
private static final Logger logger = LoggerFactory.getLogger(SingleOrderHistoryController.class.getName());
#RequestMapping(value = "/singleOrder/retrieve", method=RequestMethod.GET, produces="application/json")
public List<SingleHistoryRecord> getSingleOrderDetails(#RequestParam(value = Constants.USER_NAME, required = true) String userName, HttpServletRequest request,HttpServletResponse response) throws Exception {
logger.debug("inside SingleOrderHistoryController ");
List<SingleHistoryRecord> singleOrderHistoryList = new ArrayList<SingleHistoryRecord>();
SingleHistoryRecord record1 = new SingleHistoryRecord();
SingleHistoryRecord record2 = new SingleHistoryRecord();
record1.setClientIdentifier(userName);
record1.setSubmitDate("01/05/2017");
record1.setStatus("Complete");
record1.setReferenceID("1234555");
record1.setOrderID("test123");
record2.setClientIdentifier(userName);
record2.setSubmitDate("01/05/2017");
record2.setStatus("Complete");
record2.setReferenceID("1234555");
record2.setOrderID("test123");
singleOrderHistoryList.add(record1);
singleOrderHistoryList.add(record2);
return singleOrderHistoryList;
}
Can anyone please advise what I am doing wrong here, It is getting the source code of the page in response instead of getting the list.

How to return data from web api controller using angularjs?

Hi I am developing one web api with angularjs application. I am doing file upload module. I am facing problem in returning object once file upload is finished.
Below is my api code to save file related data to database and if it is succsfull I am returning object.
NCT_FileUpload obj = new NCT_FileUpload();
obj.file_path = uploadPath;
obj.user_id =9;
entityObject.NCT_FileUpload.Add(obj);
int result = entityObject.SaveChanges();
if (result == 1)
{
return Request.CreateResponse<NCT_FileUpload>(HttpStatusCode.OK, obj);
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "1");
}
This is my angularjs code.
$scope.uploadFiles = function () {
$scope.uploading = true;
uploadService.uploadFiles($scope)
// then() called when uploadFiles gets back
.then(function (data) {
// promise fulfilled
$scope.uploading = false;
if (data === '') {
alert("Done!!!")
$scope.formdata = new FormData();
$scope.data = [];
$scope.countFiles = '';
$scope.$apply;
} else {
alert("Shit, What happended up there!!! " + data);
}
}, function (error) {
$scope.uploading = false;
//Server Error
alert("Shit2, What happended up there!!! " + error);
}
);
};
Below is my service code in angularjs
if (typeof response.data === 'string') {
return response.data;
} else {
return $q.reject(response.data);
}
Here i want to check with object and not as string.
I am able to save data in server, If i put below code in api controller i am able to display done. But i am returning object so my data will not be empty. Currently my error function is executing. I want to handle object returned from api in success function. Is there any way to do this? Any help would be appreciated. Thank you.
return new HttpResponseMessage(HttpStatusCode.OK) ;
I think the problem here is the generic parameter. Change this:
return Request.CreateResponse<NCT_FileUpload>(HttpStatusCode.OK, obj);
To this:
return Request.CreateResponse(HttpStatusCode.OK, obj);

How to return data from Web Api controller?

Hi I am developing restfull web api application. After inserting data into database i want to return 0 for success,1 for error and data as unique id assigned to the user. I want to return above data in json format. My requirement is i have to send data to controller in json format and receive data in json format. I have following code and it is working but i want to ask few points here.
Below is my User_Creation controller code.
public result Post(Noor_Users users)
{
result obj = new result();
if (ModelState.IsValid)
{
entityObject.Noor_Users.Add(users);
int result = entityObject.SaveChanges();
if(result==1)
{
obj.success = 0;
obj.id = 5;
return obj;
}
else
{
obj.error = 1;
return obj;
}
}
else
{
obj.error = 1;
return obj;
}
}
}
My service.js file contains below code.
app.service("UserCreation", function ($http) {
this.saveSubscriber = function (sub) {
return $http({
method: 'post',
data: JSON.stringify(sub),
url: 'api/User_Creation',
contentType: "application/json"
});
}
});
This is my controller.js code.
app.controller('UserCreation', function ($scope, UserCreation) {
$scope.saveSubs = function () {
var sub = {
user_email: $scope.user_email,
user_password: $scope.user_password,
};
var saveSubs = UserCreation.saveSubscriber(sub);
saveSubs.then(function (data) {
alert(JSON.stringify(data.data));
}, function (error) {
console.log('Oops! Something went wrong while saving the data.')
})
};
});
I am expecting response in json format as below.
● status - 0 for success, 1 for failure.
● data
○ id - unique id assigned to the user
● error - error message if failed
This is working absolutelt fine. I have below line of code in webapiconfig.cs file
config.Formatters.JsonFormatter.SupportedMediaTypes
.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("text/html"));
With this line of code always i can receive data in json format. But in angularjs success call i need to stringify recieved data. If all my data is returning in json then again why i should convert it to json? Also someone can tell me is above logic is a good practice to return data? Thank you.
Try the following steps:
Add this two line of code on top of your WebApiConfig.cs
public static void Register(HttpConfiguration config)
{
config.Formatters.Clear();
config.Formatters.Add(new JsonMediaTypeFormatter());
Edit you controller action with following one
public IHttpActionResult Post(Noor_Users users)
{
result obj = new result();
if (ModelState.IsValid)
{
entityObject.Noor_Users.Add(users);
int result = entityObject.SaveChanges();
if (result == 1)
{
obj.success = 0;
obj.id = 5;
}
else
{
obj.error = 1;
}
}
else
{
obj.error = 1;
}
return Ok(obj);
}

Getting status 500 when using angularjs $http to get data from server

I am working on an asp.net mvc application and I am using Entity Framework and AngularJS in it. I am using AngularJS's $http service to call an action method and retrieve data from the server. The correct data is retrieved from the server (I confirmed this by debugging), but somehow an error occurs after the action method returns the retrieved data and the error callback function is fired instead of the success callback function. And then I get a status 500 in the browser's console.
Here are the involved blocks of codes:
(From angularjs controller)
$http({
url: rootUrl + "User/GetUser",//'#Url.Action("GetUser","User")',
method: 'POST',
params: {
uname: $scope.username,
pword: $scope.pass
}
}).then(function (response) {
alert('success!');
$scope.user = response.data;
if ($scope.user.Fullname != undefined) {
$http({
url: rootUrl + "Session/Set",
method: "POST",
data: {
"key": "curr_user",
"value": JSON.stringify($scope.user)
}
});
window.location.href = rootUrl + 'Product/List/';
} else {
//invalid login
$("input[name='password']").select();
$("#validation-summary").html("Wrong email or password.");
$scope.invalidlogin = true;
$(btnLogin).removeClass('disabled');
$(btnLogin).text("Submit");
}
(From mvc controller)
[HttpPost]
public JsonResult GetUser(string uname, string pword)
{
JBManager manager = null;
using (SE_Context db = new SE_Context())
{
try
{
manager = db.Managers
.Include("Transactions.Items")
.Where(m => m.Username == uname && m.Password == pword)
.FirstOrDefault();
//At this point, manager has the desired data
return Json(manager, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return null;
}
}
}
And here's a screenshot of the error in the browser:
Would really appreciate any help. Thanks!
UPDATE:
Everything was working fine before I used Entity Framework. (Just in case it has something to do with the issue)
I think your issue is nested objects.You can flatten object graphs that contain nested objects using DTOs (Data Transfer Objects).
You can just try simple example as like below.If it'll work then you need to extend it to work with your EF query.
public class MyDto
{
public string Name { get; set; }
}
[HttpPost]
public JsonResult GetUser(string uname, string pword)
{
JBManager manager = null;
using (SE_Context db = new SE_Context())
{
try
{
//construct the DTO here
manager = db.Managers.Select(a=> new MyDto(
{
Name = a.Name
})).FirstOrDefault(m => m.Username == uname && m.Password == pword);
return Json(manager, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return null;
}
}
}
You can read more about DTOs here : Create Data Transfer Objects (DTOs)

The current request is not a multipart request in angularJS and Spring Rest

I am trying to upload file using AngularJS on client side and Spring RESTApi on server side but getting
Error
org.springframework.web.multipart.MultipartException: The current request is not a multipart request
at org.springframework.web.method.annotation.RequestParamMethodArgumentResolver.assertIsMultipartRequest(RequestParamMethodArgumentResolver.java:216)
at org.springframework.web.method.annotation.RequestParamMethodArgumentResolver.resolveName(RequestParamMethodArgumentResolver.java:167)
.......
[http-bio-8080-exec-1] WARN org.springframework.web.servlet.PageNotFound - Request method 'POST' not supported
Rest API
Below is a simple Java Post function:
#RequestMapping(method = RequestMethod.POST)
public String saveFile(
#RequestParam("file") MultipartFile file) {
return "success";
}
In Angular, I am using Resource service to send request.
Chrome Developer Tool output
Request Payload
------WebKitFormBoundarydFRgXclyfPVixdHo
Content-Disposition: form-data; name="file"; filename="Release_Notes.txt"
Content-Type: text/plain
------WebKitFormBoundarydFRgXclyfPVixdHo--
Angular Service
function FileUploadService($resource) {
return $resource('/fileUpload/:id', {}, {
'save' : {
method : 'POST',
transformRequest: function(data, headersGetter) {
var headers = headersGetter();
headers['Content-Type'] = undefined;
if (data == undefined) {
return data;
}
var fd = new FormData();
var createKey = function(_keys_, currentKey) {
var keys = angular.copy(_keys_);
keys.push(currentKey);
var formKey = keys.shift()
if (keys.length) {
formKey += "[" + keys.join("][") + "]"
}
return formKey;
};
var addToFd = function(object, keys) {
angular.forEach(object, function(value, key) {
var formKey = createKey(keys, key);
if (value instanceof File) {
fd.append(formKey, value);
} else if (value instanceof FileList) {
if (value.length == 1) {
fd.append(formKey, value[0]);
} else {
angular.forEach(value, function(file, index) {
fd.append(formKey + '[' + index + ']', file);
});
}
} else if (value && (typeof value == 'object' || typeof value == 'array')) {
var _keys = angular.copy(keys);
_keys.push(key)
addToFd(value, _keys);
} else {
fd.append(formKey, value);
}
});
};
addToFd(data, []);
return fd;
}
}
});
}
Any hint to avoid this error?
Method assertIsMultipartRequest from RequestParamMethodArgumentResolver class is called.
The method asserts that it is a post request and content type starts with multipart/
if (!"post".equals(request.getMethod().toLowerCase())) {
return false;
}
String contentType = request.getContentType();
return (contentType != null && contentType.toLowerCase().startsWith("multipart/"));
Your content type, on the other hand, is
Content-Type: text/plain
And an exception is thrown.
#RequestMapping(method = RequestMethod.POST)
your value attribute is missing in the requestmapping it should be like this
#RequestMapping(value="/fileupload/save/{id}" ,method = RequestMethod.POST)
and use this code when creating angular resource
$resource('fileupload/save/:id',
{id:'1'}, {
save: {method:'POST', params:{charge:true}}
});
in springBoot theres not much to configure when uploading the file.
but you can add these properties to your application property file to change the file size limits.
# File size limit
multipart.maxFileSize = 3Mb
# Total request size for a multipart/form-data
multipart.maxRequestSize = 20Mb
The above issue is resolved by:
1) Creating a MultipartResolver bean in WebAppConfig.java as shown below:
#Bean
public MultipartResolver multipartResolver() {
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
return multipartResolver;
}
2) Replacing AngularJS FileUploadService (which is using Resource service) with http as shown below:
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
});
Hope it helps.

Resources