User.Identity.GetUserId () method does not work in Web Api 2 Controller

The following code works in a regular controller:

[HttpPost]
public ActionResult Custom()
{
    string name = User.Identity.GetUserName();
    string id = User.Identity.GetUserId();
    return Content(string.Format("Name:{0} </br> ID: {1}",name, id));
}

In the Web Api 2 controller, id names and strings are empty:

[HttpPost]
public IHttpActionResult Test()
{
    string name = User.Identity.GetUserName();
    string id = User.Identity.GetUserId();
    return Ok();
}

Can someone tell me why it GetUserId()works in a regular controller, but not in Api? In both cases, I logged in and GlobalConfiguration.Configure(WebApiConfig.Register);added to Application_Start () in Global.asax.cs.

And I have another problem. If I decorate my api controller with an attribute [Authorize], I cannot even access my api. The postman will direct me to the login page when I am already logged in.

[[Authorize]]
public class TestController : ApiController
{
    ....
+4
source share
4 answers

. , .

, , - WebAPI-. MVC cookie, . WebAPI, -, .

" " WebAPI , ​​ "accessToken". , , , WebAPI "", " [ ]".

, http://www.asp.net/web-api/overview/security/individual-accounts-in-web-api, , Get WebAPI. ":".

GET https://localhost:44305/api/values/1 HTTP/1.1
Host: localhost:44305
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; rv:32.0) Gecko/20100101 Firefox/32.0
Accept: */*
Authorization: Bearer imSXTs2OqSrGWzsFQhIXziFCO3rF...
X-Requested-With: XMLHttpRequest
Hide result
+1

string userId = HttpContext.Current.User.Identity.GetUserId();
+1

Below is the code to help solve this problem.

using (josd_databaseEntities entities = new josd_databaseEntities())
            {
                josddevotee user = entities.josddevotees.Where
                <josddevotee>(r => r.Devt_Email == context.UserName && r.Devt_Password == context.Password).FirstOrDefault();

                if (user == null)
                {
                    context.SetError("invalid_grant", "The user name or password is incorrect.");
                    return;
                }
                else
                {
                    string id = user.Devt_ID.ToString();
                    identity.AddClaim(new Claim(ClaimTypes.Role, "user"));
                    identity.AddClaim(new Claim("username", context.UserName));
                    **identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, id));**
                    context.Validated(identity);
                }
            }

In the controller.

public IHttpActionResult Get()
        {
            var identity = (ClaimsIdentity)User.Identity;
            return Ok(User.Identity.GetUserId());
        }
+1
source
string id = RequestContext.Principal.Identity.GetUserId();

Try using this when you have ApiController.

0
source

Source: https://habr.com/ru/post/1648392/


All Articles