Answer the question
In order to leave comments, you need to log in
User Data Extension in Asp.net Web Api 2?
I apologize in advance for a stupid question, but since I undertook to study MVC and WebApi, it nevertheless arose.
I created a project on MVC Web Api (version 2 and Visual Studio 2013). In the project settings, I specified "individual accounts" for authentication. There were no issues with this, registration, login and all other operations work fine. Now - I created a new class in the model and called it Person (well, the controller, respectively), now I want to bind the user (and I would like this to happen during registration) with a specific Person. Here I have no idea where to look at all. The second question in the topic is how then to get data from Person, depending on what is logged in. Well, the third question is how to force the authentication system to ask not just a username for user registration, but an email address.
At the moment, I have done this so far:
1. To link the user with Person
a. added field public string AppUserName { get; set; } in Person
b. changed a little POST in the controller to:
// POST api/Person
[ResponseType(typeof(Person))]
[Route("api/RegisterPersonForUser")]
[Authorize]
public IHttpActionResult PostPerson(Person person)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var result = (from p in db.People where p.AppUserName == User.Identity.Name select p).ToList();
if (result.Count > 0)
{
return StatusCode(HttpStatusCode.NotAcceptable);
}
person.AppUserName = User.Identity.Name;
db.People.Add(person);
db.SaveChanges();
return CreatedAtRoute("DefaultApi", new { id = person.Id }, person);
}
[Authorize]
[Route("api/GetUserInfo")]
public IHttpActionResult GetAssociatedPersonId()
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var result = (from p in db.People where p.AppUserName == User.Identity.Name select p).ToList();
if(result.Count > 0)
{
Person person = result[0];
return CreatedAtRoute("DefaultApi", new { id = person.Id }, person);
}
return StatusCode(HttpStatusCode.NoContent);
}
Answer the question
In order to leave comments, you need to log in
To get started, take an introductory course on MVC3 / 4 / 5, it will not take you as much time as it seems - there are simple web applications like a music store. Then read about the new authorization in MVC5 and how user properties can be "expanded" with new fields.
See how it works in practice (works, tested) on the same demo project like a music disc store, and only then start having fun with WebApi, adding functionality
I’ve already done everything, and everything works out in MVC 5 Web Application, but the web api template is built a little differently, and I can’t get it right
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question