设置用户属性的单元测试的ApiController

设置用户属性的单元测试的ApiController

本文介绍了设置用户属性的单元测试的ApiController的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

对于ApiController我的单元测试使用了一些助手方法来实例化控制器:

My unit tests for an ApiController uses some helpers methods to instantiate the controller:

public static ResourcesController SetupResourcesController(HttpRequestMessage request, IResourceMetadataRepository repo, IUnitOfWorkService unitOfWorkService)
{
    var config = new HttpConfiguration();
    var defaultRoute = config.Routes.MapHttpRoute(RouteNames.DefaultApi , "api/{controller}/{id}");
    var routeData = new HttpRouteData(defaultRoute, new HttpRouteValueDictionary { { "controller", "resources" } });

    var resourcesController = new ResourcesController(repo, unitOfWorkService)
    {
        ControllerContext = new HttpControllerContext(config, routeData, request),
        Request = request
    };
    resourcesController.Request.Properties.Add(HttpPropertyKeys.HttpRouteDataKey, routeData);
    resourcesController.Request.Properties[HttpPropertyKeys.HttpConfigurationKey] = config;

    // Compilation fail: The Property 'System.Web.Http.ApiController.User' has no setter.
    resourcesController.User = myStubUserPrincipal;

    return resourcesController;
}

我的问题是:如何设置用户属性控制器

My question is: how to set the User property for the controller?

我试过:

request.Properties.Add("MS_UserPrincipal", myStubUserPrincipal);

但是,这并不工作,要么(在resourcesController.User属性保持为空)。

But this doesn't work either (the resourcesController.User property remains null).

推荐答案

Thread.CurrentPrincipal中,这将初始化用户控制器自动属性。

Set the Thread.CurrentPrincipal, and that will initialize the User property in the controller automatically.

对于看到这个答案,但不知道如何设置个人 CurrentPrincipal
是从MSDN中提取。

For people that see this answer, but have no idea how to set CurrentPrincipal.:This code is extracted from MSDN.

Thread.CurrentPrincipal = new GenericPrincipal
(
   new GenericIdentity("Bob", "Passport"),
   new[] {"managers", "executives"}
);

这篇关于设置用户属性的单元测试的ApiController的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 23:21