Send data as multipart/form-data - asp.net

I have .NET Core back end, that receive DTO as form-data.
Here is controller
[HttpPost]
public async Task<IActionResult> Register([FromForm] RegisterDto model)
{
var result = await _authAppService.Register(model);
if (result.Code == 409)
{
return BadRequest();
}
return Ok(result.Token);
}
Here is DTO
public class RegisterDto
{
[Required]
public string Email { get; set; }
[Required]
public string Password { get; set; }
[Required]
public string PasswordConfirmation { get; set; }
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
public string GcmToken { get; set; }
}
I need to send data from Angular app via form-data
I defined model at Angular side
Here is it
export class RegisterDto{
Email: string;
Password: string;
PasswordConfirmation: string;
FirstName: string;
LastName: string;
}
And this is how I try to do form-data sending
register(){
const formData = new FormData();
formData.append(this.registerObject);
}
in append method I have this erroк
Expected 2-3 arguments, but got 1.ts(2554)
How I can send DTO via form data?

You can't append the whole object without giving it a field name. As the error says it acceptes 2-3 arguments however you are only providing one argument without giving it a field name.
register(){
const formData = new FormData();
formData.append('regObj', this.registerObject);
}
however it's good if you append each field as formdata value such as.
formGroup: FormGroup;
formData: FormData;
register() {
this.formData.append('Email', this.formGroup.controls.Email.value);
this.formData.append('Password', this.formGroup.controls.Password.value);
this.formData.append('FirstName', this.formGroup.controls.FirstName.value);
this.formData.append('LastName', this.formGroup.controls.LastName.value);
// call your service and send it
}

Related

How do I update a custom property of an IdentityUser through api controller in ASP.NET Core?

So I'm working on an api controller and I have an update method like this:
[HttpPost("update")]
public async Task<IActionResult> Update([FromBody] UpdateModel model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var user = _userManager.Users
.Include(u => u.Address)
.FirstOrDefault(u => u.UserName == model.Email);
if (user == null)
{
return BadRequest(new {Message = "User doesn't exist"});
}
user.FirstName = model.FirstName;
user.LastName = model.LastName;
user.Address = model.Address;
await _userManager.UpdateAsync(user);
return Ok(new {Message = "User has been updated successfully"});
}
When updating the user through an api call, the user gets updated, except for the address.
This is the address:
public class Address : Entity
{
public string AddressLine { get; set; }
public string PostalCode { get; set; }
public string City { get; set; }
}
And the update model:
public class UpdateModel
{
[Required]
[MinLength(3)]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
[Required]
[EmailAddress]
public string Email { get; set; }
public Address Address { get; set; }
}
I've done proper migrations, and I tried setting a breakpoint on the user variable. The variable indeeds hold an Address before updateAsync is called.
The user's firstName and lastName both get updated in a POST request, but the address remains null.
Does anyone know why this would happen?
I think you are set one to one mapping between User & Address. So first of all check the relation mapping & still not work then try to make new variable of Address and after that assign this new variable to user.Address

Debugger Stops while Parsing Rest API response HttpClient, Xamarin Forms

I am trying to parse response from ASP.NET Core Web API. I am able to parse the response JSON into C# object successfully but app crashes without throwing any error when the parsed C# object is returned to the ViewModel.
in ViewModel
ApiResponse response = await _apiManager.GetAsync<ApiResponse>("authentication/GetUserById/1");
Response JSON:
{
"result": {
"id": 1,
"userType": 1,
"firstName": “FirstName”,
"middleName": null,
"lastName": “LastName”,
},
"httpStatusCode": 200,
"httpStatusDescription": "200OkResponse",
"success": true,
"message": "hello"
}
HttpClient GetAsync() method:
public async Task<TResult> GetAsync<TResult>(string endpoint)
{
HttpResponseMessage httpResponse = _httpClient.GetAsync(endpoint).GetAwaiter().GetResult();
httpResponse.EnsureSuccessStatusCode();
TResult t = default(TResult);
if (httpResponse.IsSuccessStatusCode)
{
string serialized = await httpResponse.Content.ReadAsStringAsync();
t = JsonConvert.DeserializeObject<TResult>(serialized);
}
return t;
}
App crashes (debugger stops without any error) at "return t" statement. Here, _httpClient is a singleton object of HttpClient using DI.
TResult model is ApiResponse object
public class User
{
[JsonProperty("id")]
public int UserId { get; set; }
[JsonProperty("userType")]
public int UserType { get; set; }
[JsonProperty("firstName")]
public string FirstName { get; set; }
[JsonProperty("middleName")]
public string MiddleName { get; set; }
[JsonProperty("lastName")]
public string LastName { get; set; }
}
public abstract class ResponseBase
{
[JsonProperty("httpStatusCode")]
public int HttpStatusCode { get; protected set; }
[JsonProperty("httpStatusDescription")]
public string HttpStatusDescription { get; protected set; }
[JsonProperty("success")]
public bool Success { get; protected set; }
[JsonProperty("message")]
public string Message { get; protected set; }
}
public class ApiResponse : ResponseBase
{
[JsonProperty("result")]
public User Result { get; set; } = new User();
}
There are two issues:
1. when the following statement executes, app crashes and debugger stops without throwing any error.
HttpResponseMessage httpResponse = await _httpClient.GetAsync(endpoint).ConfigureAwait(false);
But when GetAsync() is called with .GetAwaiter().GetResult(), network call is placed successfully. I do not understand why ConfigureAwait(false) fails.
HttpResponseMessage httpResponse = _httpClient.GetAsync(endpoint).GetAwaiter().GetResult();
why the following call fails and app crashes? How can I return parsed C# object to the calling code?
return JsonConvert.DeserializeObject(serialized);
Please advise.
Try this
try
{
var result = await httpClient.GetAsync(endpoint);
var response = await result.Content.ReadAsStringAsync();
data = JsonConvert.DeserializeObject<TResult>(response);
}
catch (Exception exp)
{
Console.Write(exp.InnerMessage);
}
Make sure that you have installed Newtonsoft.Json

Using Firesharp in Xamarin.Forms to get Data from Firebase Database

I want to push and get Recipe-Data from my Firebase Database in Xamarin.Forms with the Firesharp Plugin.
My Model Class is the Recipe Class:
public class Recipe
{
public string title { get; set; }
public string workTime { get; set; }
public string degreeOfDifficulty { get; set; }
public string caloriesPerPerson { get; set; }
public string preparation { get; set; }
public string cookingBakingTime { get; set; }
public string restTime { get; set; }
public int portions { get; set; }
public string pictureSource { get; set; }
public List<Ingredient> ingredients { get; set; }
public Recipe()
{
ingredients = new List<Ingredient>();
}
}
So Push Recipe-Objects to the Firebase DB works:
public async Task PushRecipe(Recipe recipe)
{
IFirebaseClient client = new FirebaseClient(config);
client.Push("Recipes", recipe);
}
Firebase Example
But when i want to get Data from the Database i get an Error..
public async Task<List<Recipe>> GetAllRecipes()
{
IFirebaseClient client = new FirebaseClient(config);
FirebaseResponse response = await client.GetAsync("Recipes");
try
{
List<Recipe> recipelist = response.ResultAs<List<Recipe>>();
return recipelist;
} catch (Exception e){
}
return null;
}
After this:
List<Recipe> recipelist = response.ResultAs<List<Recipe>>();
this Exception comes..
"{Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[dignaBon_App.Models.Recipe]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correc…}"
I don´t understand why i can´t get Data from the Database back..
Can someone help me?
You need instatiate the "config" with your firebase secret address key. Go to your Firebase console for this.

web api method to return data in json format?

I am making a web api call and I want the controller method to return data in json format.
The model class I used is User.cs :
public partial class User
{
public int UserID { get; set; }
public string city { get; set; }
public string email { get; set; }
public string firstName { get; set; }
public string lastName { get; set; }
public string phone { get; set; }
public string password { get; set; }
}
I want to return all the users email data in json format through the following controller method.
public string GetUsers()
{
IEnumerable<User> users = db.Users.ToList();
var jsonSerialiser = new JavaScriptSerializer();
var json = jsonSerialiser.Serialize(users);
return json;
//string json = JsonConvert.SerializeObject(users);
//return json;
}
All I am getting is empty json like:
[]
Please help. I have covered all the methods recommended on stackoverflow.
This is a lot simpler than you think, you do not need to use a jsonSerializer.
You can change your method to the following:
public List<string> GetEmails()
{
return db.Users.Select(e => e.email).ToList();
}
Then if the client specifies application/json the content is returned as json.
Please note with the above, I am only sending back the email address and not the full user details as I very much doubt you will want to send passwords out as json.

IdentityUser: "Name cannot be null or empty"

I've been trying to inherit IdentityUser to make my own class which uses Identity and still writes to my database and I keep getting this error when I try to call my registration post method:
{
"$id": "1",
"Message": "The request is invalid.",
"ModelState": {
"$id": "2",
"": [
"Name cannot be null or empty."
]
}
}
I tried number of things, but nothing works.For example when I try to set UserName field of IdentityUser it says it's impossible because it doesn't exist in the context.
The important thing to mention would be that I am using ADO.NET database first model for the account :)
This is the class:
public partial class Account :IdentityUser
{
public Account()
{
this.Families = new HashSet<Family>();
}
public long idAccount { get; set; }
public string email { get; set; }
public string password { get; set; }
public string firstName { get; set; }
public string lastName { get; set; }
public virtual ICollection<Family> Families { get; set; }
}
This is my authentication repository class:
public class AuthRepository :IDisposable
{
private DAKPAKEntities _ctx;
private UserManager<Account> _userManager;
public AuthRepository()
{
_ctx = new DAKPAKEntities();
_userManager = new UserManager<Account>(new UserStore<Account>(_ctx));
}
public async Task<IdentityResult> RegisterUser(Account userModel)
{
Account user = new Account
{
firstName = userModel.firstName,
lastName = userModel.lastName,
email=userModel.email
};
var result = await _userManager.CreateAsync(user,userModel.password);
return result;
}
}
And this is the controller that calls the repository:
// POST api/Account/Register
[AllowAnonymous]
[Route("Register")]
public async Task<IHttpActionResult> Register(Account userModel)
{
IdentityResult result = await _repo.RegisterUser(userModel);
IHttpActionResult errorResult = GetErrorResult(result);
if (errorResult != null)
{
return errorResult;
}
return Ok();
}
I am new to this, and am out of options to try. I did almost everything that's usually suggested for this type of error, please help :)
It looks like you haven't done everything that is required in order to change the way ASPNet Identity stores the user information in the database.
Suggest you start here: Overview of Custom Storage Providers for ASP.NET Identity

Resources