Creating Parameter's for Api request in Alamofire. - ios

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?

Related

Call Web Api from MVC Controller and post

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?

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:''};

MVC.net Hiding Fields within a model

So I am creating a an API with ASP.net MVC Web API. I currently have a model which contains the fields for a user in the database. I have a password field on this model. See below for an example.
public class Account
{
[Key]
public Guid UserId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string UserName { get; set; }
public string Email { get; set; }
public string Password { get; set; }
}
I return this model using JSON when a controller method is called over HTTP. This works fine.
My question is, how do I stop the password field being returned alongside with it? Without removing the field altogether.
My initial idea is to create another model class which I use to return the data without the password field, but I'd rather not repeat myself for the sake of one field.
Any suggestions?
You should be able to mark these fields with
[JsonIgnore]
[XmlIgnore]
public string Password { get; set; }
Preventing these fields to be used in either JSON or XML requests.

How to signup/login Parse User from authenticated Twitter oauth_token in .NET?

I've used the OAuth1Authenticator class from the Xamarin.Auth component library to allow users to login via Twitter. It authenticates correctly and gets me a response which has the following: oauth_token, oauth_token_secret, user_id, screen_name, oauth_consumer_key, oauth_consumer_secret.
Here is my code
OAuth1Authenticator twitterAuthenticator = new OAuth1Authenticator(Constants.Twitter.CONSUMER_KEY, Constants.Twitter.CONSUMER_SECRET, new Uri(Constants.Twitter.REQUEST_TOKEN_URL), new Uri(Constants.Twitter.AUTHORIZE_URL), new Uri(Constants.Twitter.ACCESS_TOKEN_URL), new Uri(Constants.Twitter.CALLBACK_URL));
twitterAuthenticator.Completed += async (sender, e) =>
{
if (!e.IsAuthenticated)
{
return;
}
string oauth_token = e.Account.Properties["oauth_token"].ToString();
The question is how do I then use that response to signup/signin a Parse User ? i.e. I want a ParseUser created on the parse database via the Twitter token and the session should be taken care of, same way it works for sign-via-Facebook using ParseFacebookUtils class
Problem is Parse doesn't support Login via Twitter in Xamarin, however, I believe parse does support any type of 3rd party authentication in an alternative way as shown below but I don't know how to do it.
Here are the most relative links
https://parse.com/tutorials/adding-third-party-authentication-to-your-web-app but the problem in this link is that it's made as a webpage button, don't know how to use that on a mobile, and it's for GitHub don't know how to use it for Twitter instead (Twitter is only OAuth1)
http://blog.parse.com/2013/12/03/bring-your-own-login/ This is exactly what I need but it needs a session Token, doesn't work with the oauth_tokens that twitter responds back to me, hence don't know how to use the method mentioned in the link
https://github.com/auth0/rules/blob/master/parse.md This looks like the solution, however I don't know how to use it, it does show the twitter icon so it should work with twtiter but how do I get that to work in .NET Update: I've found this xamarin component http://components.xamarin.com/view/Auth0Client which gets me closer to use the method mentioned in the first link in this paragraph, yet I'm still lost and don't know how to link autho0 to parse
All in all, I'm lost in this maze and really wish anyone could help me out.
I don't have a Twitter account so I can't test this but it looks like your POST DTO would be this:
public class TwitterAuthRequest
{
public AuthData authData { get; set; }
}
public class Twitter
{
public string id { get; set; }
public string screen_name { get; set; }
public string consumer_key { get; set; }
public string consumer_secret { get; set; }
public string auth_token { get; set; }
public string auth_token_secret { get; set; }
}
public class AuthData
{
public Twitter twitter { get; set; }
}
With a response DTO like this:
public class TwitterAuthResponse
{
public string username { get; set; }
public string createdAt { get; set; }
public string updatedAt { get; set; }
public string objectId { get; set; }
public string sessionToken { get; set; }
public AuthData authData { get; set; }
}
public class Twitter
{
public string id { get; set; }
public string screen_name { get; set; }
public string consumer_key { get; set; }
public string consumer_secret { get; set; }
public string auth_token { get; set; }
public string auth_token_secret { get; set; }
}
public class AuthData
{
public Twitter twitter { get; set; }
}
Don't forget to put in the headers:
("X-Parse-Application-Id", ApplicationId)
("X-Parse-REST-API-Key", ApplicationKey)
Source: https://parse.com/docs/rest#users
EDIT:
I have a created a draft for how you would use the DTO's:
public static class TwitterLoginProvider
{
public static Task<ServiceResponse<TwitterAuthResponse>> Login(
Twitter twitterInfo,
string applicationId,
string apiKey,
IRestClient restClient)
{
var request = new TwitterAuthRequest ()
{
authData = new AuthData ()
{
twitter = twitterInfo
}
};
restClient.AddHeader ("X-Parse-Application-Id", applicationId);
restClient.AddHeader ("X-Parse-REST-API-Key", apiKey);
return restClient.PostAsync<TwitterAuthResponse>("https://api.parse.com/1/users", request, Format.Json);
}
}
When you get the response from Xamarin.Auth, use that info to create a Twitter object and pass it to the IRestClient. As a response from the service you will get a response with the session information.
IRestClient interface: https://github.com/sami1971/SimplyMobile/blob/master/Core/SimplyMobile.Web/IRestClient.cs
Sample implementation: https://github.com/sami1971/SimplyMobile/blob/master/Core/SimplyMobile.Web/RestClient.cs
Alternatively you could use RestSharp: http://restsharp.org/

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