Call Web Api from MVC Controller and post - asp.net-mvc

I have a logger in Web Api controller, which inserts posted files in the log txt file. This is my ValuesController's Post method:
public void Post([FromBody] SmsObject sms)
{
Logger.Info(string.Format("Text : {0}, Amount : {1}, Phone : {2}", sms.SMSText, sms.Amount, sms.Phone));
}
this is my Model :
public class SmsObject
{
public string SMSText { get; set; }
public decimal Amount { get; set; }
public string Phone { get; set; }
}
When I'm testing this Web API in Postman, it works. But now I want to call this method from another MVC solution and post data.
How can I use MVC controller to call this Web API?

Related

Azure asp.net web api working fine now how do I get iOS talk to Azure web server?

I am new to iOS.
I searched similar questions but couldn't find right answer for my situation.
I created asp.net web api (slected only web api option not selected MVC option)
But I made model Account and controller AccountsController which is an ApiContoller
in my AccountsController:
[Authorize]
// GET: api/Accounts
public IQueryable<Account> GetAccounts()
{
return db.Accounts;
}
// GET: api/Accounts/5
[ResponseType(typeof(Account))]
[Route("api/account/{id}")]
public IHttpActionResult GetAccount(int id)
{
Account account = db.Accounts.Find(id);
if (account == null)
{
return NotFound();
}
return Ok(account);
}
And my Account model:
public class Account
{
public int Id { get; set; }
public string UserName { get; set; }
public string UserEmail { get; set; }
public decimal Rebate { get; set; }
public decimal MemCom { get; set; }
}
When I run http://tresmorewebapi.azurewebsites.net/api/accounts
I get all lists of accounts.
How can I create simple ios app in swift that shows lists of Account table? And after I inserted [Authorize] to AccountsController, I get error message Authorization has been denied for this request by same http GET request http://tresmorewebapi.azurewebsites.net/api/accounts
How can I send http request with authorization..?
I guess anyone who read this question can POST to my server..??
If someone can lead me to this step.. I think I can get further..
Thank you very much!

Call MVC post method from postman and send parameters to it

I need to test this mvc method from postman, it is working in Browser.
[HttpPost]
[Route("login")]
public async Task<ActionResult> Login(LogInRequest logInRequest)
{
User user = null;
if (ModelState.IsValid)
{
.....
This is LogInRequest Class:
public class LogInRequest
{
[Required]
public string UserName { get; set; }
[Required]
public string Password { get; set; }
public string Token { get; set; }
public bool IsResetPassword { get; set; }
public bool IsThankYouPage { get; set; }
}
I am not sure how to sent the LogInRequest parameter using Postman. anything I try it is not hitting the breakpoints in first line of this method.
This is how I call the local URL and send parameter to this method.
I know this an old question but it may be helping the others.
You should use the Route which you provided in the controller e.g
[Route("login")]
Url in postman call should be like this
HTTP:/localhost:12xx3/login.

Creating Parameter's for Api request in Alamofire.

I am using Xcode and swift 2 for creating a chat app for iOS platform. We are using asp.net mvc for creating the Api and mongodb as our database. Our SignUp model Contains Fields for Email and Password.
My Model is
public class SignUpViewModel
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string _id { get; set; }
public string Email { get; set; }
public string Password { get; set; }
}
And the Api method is
public JsonResult Sign_Up(SignUpViewModel signupviewmodel)
{
}
How can i pass and retrieve parameter's (data) as Model using Alamofire?

Passing AngularJS Model to Web API, Model is Null

In need of some advice, I am trying to create a register/login section on a SPA project I am working on.
I am using AngularJS for the front end and MVC Web API for the back end.
Problem I am having is my model is showing as null when the Web API's POST method is hit.
Here is my code:
AngularJS Controller
SugarGlidersMain.controller('RegisterController', ['$scope', 'UserService', '$location', '$rootScope', 'FlashService', function ($scope,UserService, $location, $rootScope, FlashService) {
$scope.user = [{ID:'',Username:'',Password:'',Email:'',LastLogin:'',Role:'User', FirstName:'',LastName:''}]
$scope.register = function() {
var data = $scope.user;
UserService.Create($scope.user)
.then(function (response) {
if (response.success) {
FlashService.Success('Registration successful', true);
$location.path('/login');
} else {
FlashService.Error(response.message);
}
});
}
Note: Firstname, Lastname, Password and Email are bound to input fields in the html
AngularJS service
function Create(user) {
return $http.post('/api/User', user).then(handleSuccess, handleError('Error creating user'));
}
Note: user contains data when being sent to the Web API
WebAPI
// POST api/user
public void Post([FromBody]UserModel user)
{
string firstname = user.FirstName;
string lastname = user.LastName;
}
MVC Model
public class UserModel
{
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int ID { get; set; }
[Required]
public string Username { get; set; }
[Required]
public string Password { get; set; }
[Required]
public string Email { get; set; }
public DateTime? LastLogin { get; set; }
public string Role { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
Does the data structure matter when passing a model to web API eg could I simply pass over Username, Email and Password without the other properties to the Web API and still use UserModel?
Thank you in advance.
In you current case you are passing $scope.user array to post but the thing is though you passed whole data in the array first element controller method won't understand that object, because its different than what actually the method is expecting. So for getting correct object on server you should pass correct JSON.
When you are passing object to API it should pass single user object rather than passing the whole array
UserService.Create($scope.user[0])
OR
Better change user object declaration to object
$scope.user = {ID:'',Username:'',Password:'',Email:'',LastLogin:'',Role:'User', FirstName:'',LastName:''};

Pass Lists to MVC controller Action using POSTMan chrome extention

I am using Postman Chrome extension to test my MVC service API.
The model that I pass to the controller looks as follows:
public class ActivateBenefitRequestModel
{
public int BenefitID { get; set; }
public int MemberID { get; set; }
public string Token { get; set; }
public List<AdditionalBenefitField> BenefitAdditionalFields { get; set; }
}
with
public class AdditionalBenefitField
{
public int BenefitFieldId { get; set; }
public string Value { get; set; }
}
How should I go about passing in the BenefitAdditionalFields List ?
Is it even possible?
Assuming that all you're doing is building a POST request string (not familiar with the extension), I believe you can just format your request to specify individual list elements indexed with URL-encoded square brackets:
...&AdditionalBenefitFields%5B0%5D.BenefitFieldId=1&AdditionalBenefitFields%5B0%5D.Value=Foo
&AdditionalBenefitFields%5B1%5D.BenefitFieldId=2&AdditionalBenefitFields%5B1%5D.Value=Bar&...
This is how a POST request for a list of complex types looks in one of our MVC3 projects and I'm pretty sure we don't do anything special with it.
So I got it and it's pretty easy:
Just set separate text values in your form data in the PostMan extention
BenefitAdditionalFields[0].BenefitFieldId
BenefitAdditionalFields[0].Value
BenefitAdditionalFields[1].BenefitFieldId
BenefitAdditionalFields[1].Value

Resources