Calling a specific method in my Web API controller - asp.net

So I'm trying to make a call to this specific method:
[HttpGet]
public int GetLogin(string u, string p)
{
UserLogin uL = new UserLogin();
return (int)uL.Authenticate(u, p);
}
However it keeps calling this method in my Controller instead:
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
^^ Which is the generated code in the Controller.
Here Angular code for my factory and, more importantly, my URI:
var loginFactory = angular.module('loginService', ['ngResource'])
loginFactory.factory('UserLogin', function ($resource) {
return $resource('api/login?:username?:password', {}, {
query: {
method: 'GET',
params: { username: 'hunter', password: 'hunter' },
isArray:true
}
});
});
Any insight would be much appreciated. Thanks.

Change your resource to this:
$resource('api/GetLogin?u=:username&p=:password', {}, { // if that's the right route
query: {
method: 'GET',
params: { username: 'hunter', password: 'hunter' },
isArray:true
}
});

Is your request going like api/login?username=something&password=something...?
if yes, the parameter names on the action should match the query string parameter names:
public int GetLogin(string **username**, string **password**)

Related

How to get the value of a callback outside the upload function of the Vimeo class?

I'm very new to js and I'm learning Nestjs. I'm building an API to work with the Vimeo API using their Vimeo lib. To upload a video, the Vimeo class has a method called upload:
upload(
file: string | File,
params: object,
completeCallback: UriCallback,
progressCallback: ProgressCallback | undefined,
errorCallback: ErrorCallback,
): void;
upload(
file: string | File,
completeCallback: UriCallback,
progressCallback: ProgressCallback | undefined,
errorCallback: ErrorCallback,
): void;
On my service, I used it like:
async uploadVideo(#Body() video: UploadVideoDto): Promise<string> {
let videoUri: string;
this.client.upload(
video.pathToFile,
{
name: video.name,
description: video.description,
},
function (uri) {
console.log(uri);
videoUri = uri;
},
function (bytesUploaded, bytesTotal) {
console.log(bytesUploaded, bytesTotal);
},
function (error) {
throw new Error(error);
},
);
return videoUri;
}
The function (uri) { console.log(uri) } is the callback function when the upload finishes and it gives the uri that the video was uploaded to. I tried to get it on my controller, like this:
#Post('/upload')
async upload(#Body() video: UploadVideoDto) {
await this.appService.uploadVideo(video).then(function (uri): void {
console.log(uri);
});
}
The problem is that the console.log(uri) always prints undefined. How can I get that callback return from my service to my controller?
if uploadVideo should return a Promise that resolves to an string (the uri), it could be like this:
async uploadVideo(video: UploadVideoDto): Promise<string> {
return new Promise<string>((resolve, reject) => {
this.client.upload(
video.pathToFile,
{
name: video.name,
description: video.description,
},
function (uri) {
resolve(uri)
},
function (bytesUploaded, bytesTotal) {
console.log(bytesUploaded, bytesTotal);
},
function (error) {
reject(error)
},
);
})
}
Learn about JS async/await feature.

Aurelia: How to handle a async request in a view?

I have a dotnet core api that returns a FileContentResult..
return new FileContentResult(bytes, contentType)
{
FileDownloadName = Path.GetFileName(request.Filename)
};
Via postman I can read out the image perfectly fine. Now I want to read the image, via the aurelia fetch client, and show it in my html view. This is my function to retrieve the image from the api.
public image(filename: string) {
return this.http.fetch(AppConfiguration.base_url + 'assets/image',
{
method: 'post',
body: json({
filename: filename
})
});
}
I've tried to convert the blob in the response with this value converter. But I can't get that to work
Converter:
export class BlobToUrlValueConverter {
public toView(blob) {
return URL.createObjectURL(blob);
}
}
Viewmodel:
export class Dashboard {
public blob: any;
constructor(
public assets_service: AssetsService
) { }
async attached() {
let response = await this.assets_service.image('test.png');
this.blob = response.blob();
}
}
View
<div if.bind="blob">
${ blob | blobToUrl }
</div>
I'm not sure this is the right approach. Also not sure how handle the async request part of it either. What is the best way to get that image response to show in the html view? Lets say via a img tag?
I was close. Here is how I got the image to show.
Viewmodel:
export class Dashboard {
public url: string;
constructor(
public assets_service: AssetsService
) { }
async attached() {
let blob = await this.assets_service.image('test.png')
.then(response => response.blob());
this.url = URL.createObjectURL(blob);
}
}
View:
<div if.bind="url">
<img src.bind="url">
</div>
EDIT:
Found a better solution using parts written above:
The exported function that does the call (for reusability on both ts and html sides):
export function image_request(filename: string): Promise<Response> {
let http = new Http();
return http.fetch(<your-url-that-fetches-the-image>,
{
method: 'post',
body: json({
filename: filename
})
});
}
Value converter that uses above function
import { image_request } from './AssetsRequests';
export class ImageRequestValueConverter {
public toView(filename: string) {
return image_request(filename);
}
}
The important and most awesome part of the solution. Many thanks to http://www.sobell.net/aurelia-async-bindings/
for getting me on my way. You can override the binding behaviour. You can use this override to process async
Promise in a view in combination with a value converter.
export class AsyncImageBindingBehavior {
public bind(binding, source): void {
binding.originalupdateTarget = binding.updateTarget;
binding.updateTarget = (target) => {
// When we have a promise
if (typeof target.then === 'function') {
// Set temp value to loading so we know its loading
binding.originalupdateTarget('Loading...');
// Process the promise
target
.then(response => response.blob())
.then(blob => binding.originalupdateTarget(
URL.createObjectURL(blob)
));
}
else {
binding.originalupdateTarget(target);
}
};
}
unbind(binding) {
binding.updateTarget = binding.originalupdateTarget;
binding.originalupdateTarget = null;
}
}
Finally the view is very simple
<img src="${ 'test.png' | imageRequest & asyncImage }">

What is the issue with asp.net route

This is from asp.net 5 / mvc 6. I have two controller methods, each takes a single parameter and each returns a string. One method takes a string parameter and the other takes a simple object. The method that takes the string parameter does not work (the value for the incoming parameter is always null). The call that passes in the simple object does work. I am making the calls to these methods from inside an angular controller using the $http service. I must be doing something wrong that is very simple, but I don't see it.
Here is the code for the controller class:
[Route("api/[controller]")]
public class ValuesController : Controller
{
[HttpPost("PostWithStringParam")]
public string PostWithStringParam([FromBody] string val)
{
return val ?? "<null>";
}
[HttpPost("PostWithInputparam")]
public string PostWithInputParam([FromBody] TestInputClass val)
{
string ret = "<null>";
if (val != null)
{
ret = $"First Name: {val.Name}, City: {val.City}";
}
return ret;
}
}
Here is the relevant code from the angular controller. Note the the "go" function is wired up to ng-click from a button.
vm.inputObject = {
name: "George",
city: "Chicago"
}
vm.inputString = "some data";
var callApi = function(url, data) {
$http({
method: "POST",
url: url,
data: data
}).then(
function (result) {
alert(result.data);
},
function (error) {
alert(error.status);
}
);
}
var callStringApi = function() {
var url = "api/values/PostWithStringParam";
callApi(url, vm.inputString);
}
var callObjectApi = function () {
var url = "api/values/PostWithInputParam";
callApi(url, vm.inputObject);
}
vm.go = function() {
callStringApi();
callObjectApi();
}
Can someone please tell me why the method that takes the input string doesn't work??
Thanks!
You need to strinfigy the data and specify the contentType as application/json when sending data. The default model binder will be able to map the posted data then.
var callApi = function(url, data) {
$http({
method: "POST",
url: url,
data: JSON.stringify(data),
contentType:"application/json"
}).then(
function (result) {
alert(result.data);
},
function (error) {
alert(error.status);
}
);
}

Ember-cli & fullCalendar

Senario is:
mcalendar: model,
mevent: model,
relationship: mcalendar has_many mevents,
in the mcalendar.show route I have:
model: function(params) {
return this.store.find('mcalendar', params.mcalendar_id);
},
what I want to do is:
to have a function in the mcalendar.show route to return all mevents of mcalendar in the form of an array. Something like this:
A HOOK(maybe afterModel): function(){
//return all mevents like:
return {
events: Ember.A([
{
title: mevent.get('title'),
start: mevent.get('start')
}])
the purpose is to use this array for feeding fullCalendar. I have tried some ways but none of them was successful.
Ember cli: 0.2.7
Thanks
are your mevents returned in the payload when requesting mcalendar? if so, you could do this in the setupController hook instead like...
setupController: function(controller, model) {
controller.set('events', model.get('mevents').toArray());
}
afterModel: function () {
var _this = this;
var model = this.modelFor(this.routeName);
return model.get('mevents').then(function(mevents) {
var allMevents = mevents.map(function(mevent){
return {
title: mevent.get('title'),
start: mevent.get('start')
};
});
_this.controllerFor('mcalendars.show').set('events', allMevents);
});
},

calling one of multiple services in angularJS $resource

Is there anything wrong with this code where I am trying to have one service method point to different restful services?
var phonecatServices = angular.module('phonecatServices', ['ngResource']);
phonecatServices.factory('Phone', ['$resource',
function ($resource) {
return {
pList: $resource('/:url/:phoneId.json.htm', {}, {
query: { method: 'GET', params: { url: 'MyAngularScripts', phoneId: 'jsonPhonedata' }, isArray: true }
}),
pDetail: $resource('/Content/PhonesData/:phoneId.json.htm', {}, {
query: { method: 'GET', params: { phoneId: $routeParams.phoneId }, isArray: false }
})
};
}]);
Then in my controller I call the pList like this:
$scope.phones = Phone.pList.query();
The service method doesnt get called with any of the code above. However if I change the service to this:
var phonecatServices = angular.module('phonecatServices', ['ngResource']);
phonecatServices.factory('Phone', ['$resource',
function ($resource) {
return $resource('/:url/:phoneId.json.htm', {}, {
query: { method: 'GET', params: { url: 'MyAngularScripts', phoneId: 'jsonPhonedata' }, isArray: true }
});
}]);
and call from the controller like this:
$scope.phones = Phone.query();
IT works. What is wrong with the service where I have multiple restful calls declared? SOmething wrong with the way its configured or the way I am calling it?
The 1st approach should be working fine as well.
The only oroblem is that you are trying to access a property of $routeParams, without first injecting it via DI, thus resulting in an Error being thrown.
If you correct this, everything should work as expected.

Resources