HttpContext.Current.Request with Angular ui-router - c#

Using Asp.Net I am capturing the request of an AngularJS Route as it loads. The route is /FST/#/quickstart. I am trying to capture that route with:
var currentUrl = HttpContext.Current.Request.RawUrl;
however, the RawUrl doesn't contain the #/quickstart subpart. There doesn't seem to be any thing in the Request than can tell me the full URL. How can I get the target URL?

You Can use a $http interceptor to add the current route as a header to your web api request
$httpProvider.interceptors.push(['$q','$location' function($q, $location) {
return {
'request': function(config) {
config.headers.ClientSideUrl = $location.path();
return config || $q.when(config);
},
'requestError': function(rejection) {
return $q.reject(rejection);
},
'response': function(response) {
return response || $q.when(response);
},
'responseError': function(rejection) {
return $q.reject(rejection);
}
};
}]);
And then access the header server side:
HttpContext.Current.Request.Headers.GetValues("ClientSideUrl").FirstOrDefault();

Related

Unable to get posted data with Angular from asp.net

I'm sending a post request to my asp.net server from angular and i tried printing the values of my custom model class (SchoolModel) and it's all the values corrent inside angular. But when i try to get these values on asp.net it doesn't return anything from inside the object. Please help me if i'm missing something.
My angular code request
const headers = {'Content-Type': 'application/json', };
const body = { schoolData };
this.http.post<any>(this.baseUrl + "Api/CreateSchool", body, { headers }).subscribe(response => {
console.log(response);
}, error => console.error(error));
My ASP.NET code:
[HttpPost]
[Route("Api/CreateSchool")]
public bool CreateNewSchool(SchoolModel schoolData)
{
bool schoolCreated = false;
// IT PRINTS SCHOOL NAME ONLY
Console.WriteLine("SCHOOL NAME " + schoolData.Name);
return schoolCreated;
}
Use FromBody attribute.
public bool CreateNewSchool([FromBody]SchoolModel schoolData)
{
I had to use JSON.stringify(body) to make it work

Angular JS $http get call works in Chrome and returns a null in FireFox

I have an MVC app using AngularJS. We do not use WebAPI. So, the angularJS would just be calling the MVC Controllers. These calls work fine in IE & Chrome. However, in Firefox and Safari I tried for hours to get it up and running without any result. As you can see in the code below, I do have a LoginController.js file and LoginService.js file. The service.js file returns a promise object back to the controller. In firefox on error the data is null, headers are emptry, statusText is empty and status is -1. I do not see if this has anything to do with CORS. But I do not have any cors going on in here as the service just calls the MVC Controller.
LoginController.JS file
app.controller('LoginController',
function ($scope, LoginService) {
$scope.schoolList = null;
$scope.SelectedDistrictId = null;
$scope.isFLUser = $("#isFLUser").val();
$scope.User =
{
userName: "",
password: "",
Email: null,
firstName: "",
lastName: "",
roleId: null,
districtId: null,
schoolId: null,
districtName: "",
schoolName: "",
isFL: $("#IsFL").val()
}
$scope.validateUser = function () {
$("#LoginErrorSpan").hide();
var form = $('form');
$.validator.unobtrusive.parse(form);
if (form.valid()) {
$("#spinnerdiv").show();
debugger;
var promise = LoginService.validateUser($scope.User);
promise.then(function (result) {
debugger;
$("#spinnerdiv").hide();
if (result.data.InvalidUser === false) {
if (result.data.PwdchangeCount > 0) {
window.location.href = "/Login/Welcome";
}
else {
window.location.href = "/Login/ChangePassword";
}
} else {
$("#LoginErrorSpan").show();
}
},
function (result) {
debugger;
console.log(result.headers());
});
}
}
});
LoginService.JS File
var app = angular.module('app', []);
app.factory('LoginService',
function ($http) {
return {
validateUser: function (scopeUser) {
return $http({
url: "/Login/ValidateUser",
method: "GET",
params: {
userName: scopeUser.userName,
//password: encodeURIComponent(scopeUser.password),
password: scopeUser.password,
isFL: scopeUser.isFL
}
});
}
}
});
I have been trying to debug this for the last 8 hours with all the solutions I could find online.
Maybe if you are just opening html documents directly from the browser, to fix this you will need to serve your code from a webserver and access it on localhost. Open that file by an IDE (Visual studio, Eclipse etc) as a web site project.
AngularJS Error: Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, https

Get request origin in C# api controller

Is there a way how can I can get request origin value in the api controller when I'm calling some api endpoint with ajax call?
For example I'm making this call from www.xyz.com:
$http({
url: 'http://myazurewebsite.azurewebsites.net/api/ValueCall/CheckForExistingValuers',
method: "GET",
params: { loanID: $scope.loanIdPopup }
}).success(function (data) {
}).error(function (data) {
});
Once on the api side, how can I get the www.xyz.com value?
CORS is working properly.
What you're looking for is probably the origin-header. All modern browsers send it along if you're doing a cross domain request.
In an ApiController you fetch it like so:
if (Request.Headers.Contains("Origin"))
{
var values = Request.Headers.GetValues("Origin");
// Do stuff with the values... probably .FirstOrDefault()
}
You can grab it from the API methods via current HTTP request headers collection:
IEnumerable<string> originValues;
Request.Headers.TryGetValue("Origin", out originValues)
var originValue = Request.Headers["Origin"].FirstOrDefault();
// or
StringValues originValues;
Request.Headers.TryGetValue("Origin", out originValues);

How to call API in c# using angularjs

Hi I am calling my API using below code
$http.get('/api/controller/method?param=value').
then(function (response) {
if (response.status == 200) {
console.log(response.data);
}
});
It is working fine in my local machine (http://localhost/api/controller/method?param=value).
But when I deployed it in server with application name app, it is not able to call the API(http://server-ip/app/api/controller/method?param=value).
Obviously, it won't, as URL are different. So what is the correct way to call an API in c# so that it will work in any server.
What I have tried:
1. URL.Action : It is not working in this case.
2. I don't want to Use #HTML.hidden
3. Call starting with or without slash (/)
I usually solve this by using a factory like this -
First in the .cshtml page I load all the angular js required.
Then create a factory for the baseURL like this -
function(angular){
var module = angular.module('NameOfMyModule'); //gt the module
module.factory('BaseUrl', function(){
return '#Url.Action("Action", "Controller")';
});
}(window.angular);
Then inject that BaseURL inside the controller -
....
module.controller('SomeController', [...., 'BaseUrl', function(...., BaseUrl){
$scope.baseUrl = BaseUrl;
}]);
....`
Finally prepend it in the url
$http.get($scope.baseUrl + /...../).then(....);
I'm not sure if I undestood your question correctly, but I'm using angular constant to set server url
angular.constant("CONSTS", {
"DEV_URL": "http://localhost:12345",
"LIVE_URL": "http://server-ip/app"
})
and then in $http call
$http.get(CONSTS.DEV_URL + '/api/controller/method?param=value').
then(function (response) {
if (response.status == 200) {
console.log(response.data);
}
});
I'm sure there is a way to automate this (gulp, grunt), but I didn't get there yet.
When deploying the app I would just manually change the constant.
If I'll find outomatic way to it I'll update the answer.
Hope this helps a bit...
I don't know your build process etc. but usually you can store application path in some constant value in Angular and use it when calling your API as a prefix.
If you have some kind of automated build, it is easy to prepare deployment packages with changed values(by using Gulp/Grunt/TeamCity/Octopus, whatever you like).
//controller
app.controller("sampleController", function($scope, commonService) {
//post
$scope.postData = function() {
var command = {}
commonService.postSample(command);
}
//get
commonService.getSample().then(function(data) {
$scope.permissionList = data;
});
});
//service
app.service('commonService', function($http, $q) {
this.postSample = function(command) {
var deferred = $q.defer();
$http({
method: 'POST',
data: command,
url: '/Attendance/CreatePersonDailyLeave'
})
.success(function(data) {
deferred.resolve(data);
})
.error(function(data) {
deferred.reject(data);
});
return deferred.promise;
}
this.getSample = function(id) {
var deferred = $q.defer();
$http({
method: 'GET',
async: true,
url: '/Attendance/GetRoles?id=' + id
})
.success(function(data) {
deferred.resolve(data);
})
.error(function(data) {
deferred.reject(data);
});
return deferred.promise;
}
});

MVC Jquery POST data, redirect to url from ActionResult

I am currently working with mvc. I have a page with more than one button on, which does complicate things a little. However the button I am using calls a jquery function to post data to the controller. This works as expected and data reaches the action and the action does everything expected except redirect.
The function posts data to the controller, or allows the controller to see the values and build up a url to then redirect to. However the redirect doesnt work, and the function calls a success function as expected. If I put the data return into an alert the code for the page is returned in the alert window not the url.
Here is the code:
<input type="submit" value="Assign" name="Assign" onclick="doRedirect()" />
function doRedirect() {
var action = '#Url.Action("Redirect")';
//alert(action);
var opt = {
type: "POST",
data: {
Team: $('#Team option:selected').val()
},
url: action,
success: RedirectSuccess
};
jQuery.ajax(opt);
}
function RedirectSuccess(data) {
if (data != undefined) {
data;
}
}
public ActionResult Redirect(string Team)
{
var hostName = "http://localhost/test/testpage.aspx?";
var team = "&Team=" + Team;
var filterUrl = Team;
return Redirect(filterUrl);**//this doesnt work**
}
Instead of sending back a redirect result from the action, try sending back the URL you want to redirect to. On the client side, you read the response of the request, and do the redirect by setting window.location.href to the URL you get back from the server.
In your action, you could return the URL as JSON for instance:
return Json(new { url: filterUrl });
And in your success callback, you do this to redirect:
if (data !== undefined && data.url !== undefined) {
window.location.href = data.url;
}
This is what I did instead.
public string Redirect(string Team)
{
var hostName = "http://localhost/test/testpage.aspx?";
var team = "&Team=" + Team;
var filterUrl = hostname + Team;
return filterUrl;
}
function RedirectSuccess(data) {
if (data != undefined) {
window.location = data;
}
}
and on my search success

Categories