.Net,单页应用程序,请求来源

.Net,单页应用程序,请求来源,.net,asp.net-web-api,cross-domain,httpcontext,.net,Asp.net Web Api,Cross Domain,Httpcontext,我目前正在开发一个.NETWebAPI,它允许用Angular编写的单页应用程序与企业之间来回交换数据 SPA的一个特殊性是它总是在不同的域下运行,我已经为给定的域列表启用了CORS。因此,我的API将始终根据请求的来源来处理数据,例如: request origin domainId -------------- -------- https://www.client1.com -> client1.co

我目前正在开发一个.NETWebAPI,它允许用Angular编写的单页应用程序与企业之间来回交换数据

SPA的一个特殊性是它总是在不同的域下运行,我已经为给定的域列表启用了CORS。因此,我的API将始终根据请求的来源来处理数据,例如:

request origin                   domainId
--------------                   --------
https://www.client1.com    ->    client1.com
https://client1.com        ->    client1.com
https://www.client2.xxx    ->    client2.com
目前,我创建了一个实用程序类,可以根据给定的请求恢复domainId:

public static class DomainId
    {
        public static string Get(HttpRequestMessage Request)
        {
            InMemoryDomainRepository repo = new InMemoryDomainRepository();

            try
            {
                IEnumerable<string> headerValues = Request.Headers.GetValues("Origin");
                var origin = headerValues.FirstOrDefault();
                return repo.GetDomainId(origin);
            }
            catch
            {
                return repo.GetDomainId("http://client1.com");
            }
        }
问题是:

编写测试用例时,没有源代码,因为我不是从浏览器中查询API。那么,如何指定请求的来源呢?据我所知,目前无法将原点设置为:

Request.Headers.SetValues("Origin", "https://client1.com");
从origin Request.Headers.GetValuesOrigin中取出DomainId;这是迄今为止我找到的最好的方法。但也许有更好的解决办法

我目前坚持以下测试方法:

[TestClass]
public class ClientControllerTests
{
    [TestMethod]
    public void TestGetProfile()
    {
        var identity = new GenericIdentity("Bob");
        Thread.CurrentPrincipal = new GenericPrincipal(identity, null);

        // how to set a Generic Domain?

        var ctrl = new ClientController();
        var result = ctrl.GetProfile();

        IHttpActionResult actionResult = ctrl.GetProfile();

        System.Diagnostics.Debug.WriteLine(actionResult);
        //Assert.IsInstanceOfType(actionResult, typeof(OkResult));
    }
}
我希望能够指定一个通用域,就像我定义一个通用标识一样

任何帮助都将不胜感激

最好的,
Mikou

你可以看看这篇文章:,但是-个人观点-我不喜欢为mock编写太多代码参见:我实际上尝试了你提到的解决方案,但出于某种原因,我收到以下错误:命名空间“System.Web”中不存在类型或命名空间名称“HttpRequestBase”。是否缺少程序集引用?我不明白为什么
[TestClass]
public class ClientControllerTests
{
    [TestMethod]
    public void TestGetProfile()
    {
        var identity = new GenericIdentity("Bob");
        Thread.CurrentPrincipal = new GenericPrincipal(identity, null);

        // how to set a Generic Domain?

        var ctrl = new ClientController();
        var result = ctrl.GetProfile();

        IHttpActionResult actionResult = ctrl.GetProfile();

        System.Diagnostics.Debug.WriteLine(actionResult);
        //Assert.IsInstanceOfType(actionResult, typeof(OkResult));
    }
}