How to populate Controller.Request in ASP.NET MVC

I want to use the properties Request, Responsethe class System.Web.Mvc.Controllerto set and read cookie files in HTTP-requests and responses. The reason for this is that it eliminates the need to write utility classes that are read from queries and populate data in some auxiliary class. I can push all such code into the user base controller (from which all my controllers are derived).

So, I have the following code in my "BaseController"

if (Request != null)
{
   HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
   if (authCookie != null)
   {
        HttpContext.User = new GenericPrincipal(new GenericIdentity(authCookie.Value), null);
        Thread.CurrentPrincipal = HttpContext.User;
   }
}

but Requestalways null. How is it populated?

+3
source share
1 answer

, . Initialize. , , . , , , HttpContext.User: .

:

public class MyAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext)
    {
        var result = base.AuthorizeCore(httpContext);
        if (result)
        {
            var authCookie = httpContext.Request.Cookies[FormsAuthentication.FormsCookieName];
            if (authCookie != null)
            {
                httpContext.User = new GenericPrincipal(new GenericIdentity(authCookie.Value), null);
                Thread.CurrentPrincipal = httpContext.User;
            }
        }
        return result;
    }
}

:

[MyAuthorize]
public abstract class BaseController: Controller
{}

: , , , /, .

+4

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


All Articles