【问题标题】:Using conditional urls during $http POST requests of angularjs service calls in ASP.Net Web API2在 ASP.Net Web API2 中 angularjs 服务调用的 $http POST 请求期间使用条件 url
【发布时间】:2015-12-05 06:49:31
【问题描述】:

我现在正在通过以下方式发送请求。

在 PROD 中(托管在本地 IIS 服务器中)-

this.post = function (Prescription) {
    var request = $http({
        method: "post",
        dataType: "json",
        url: "/SmileMakersApp/SmileMakersApp/api/PrescriptionsAPI",
        data: Prescription
    });
    return request;
}

在开发中 -

this.post = function (Prescription) {
    var request = $http({
        method: "post",
        dataType: "json",
        url: "/api/PrescriptionsAPI",
        data: Prescription
    });
    return request;
}

问题是我正在维护版本并定期通过 git 更新我的代码。因此,每当我对该文件进行新的更改时,我都必须每次都解决冲突。并且有许多类似的请求,并且为每个请求解决冲突很麻烦。有什么方法可以让我在 PROD 和 DEV 中定义不同的 url?我已经在后端做了类似的事情。

@if (HttpContext.Current.IsDebuggingEnabled)
{
    <base href="/">
}
else
{
    <base href="/SmileMakersApp/SmileMakersApp/">
}

【问题讨论】:

  • 您可以在 Angular 中使用相同的基本 href 值:document.querySelector('head > base').getAttribute('href')。

标签: asp.net angularjs asp.net-web-api2


【解决方案1】:

如果我正确理解您的问题,您要做的是配置不同的环境,例如开发、阶段和生产。由于您使用的是 Angular,因此您应该查看一个名为 angular-environement 的插件。

安装后,将environment 添加为依赖项,并根据需要为每个环境设置域和变量。

angular.module('yourApp', ['environment']).
  config(function(envServiceProvider) {

  // this is where you need to set the domains and variables for each   environment 
  envServiceProvider.config({
    domains: {
      development: ['localhost', 'dev.local'],
      production: ['acme.com', 'acme.net', 'acme.org']
  },

  vars: {
    development: {
      apiUrl: '//localhost/api',
      staticUrl: '//localhost/static'
    },

    production: {
      apiUrl: '//api.acme.com/v2',
      staticUrl: '//static.acme.com'
    }               
  }
});

    // run the environment check, so the comparison is made 
    // before controllers and services are built 
    envServiceProvider.check();
});

设置完成后,您需要将envService 注入控制器。然后您可以访问您的网址、变量等。

controller('SomeController', ['$scope', 'envService', function($scope, envService) {
    // gets the current environemt
    var environment = envService.get(); 

    // sets the desired environment
    envService.set('production');

    // gets the desired environment variable.
    var apiUrl = envService.read('apiUrl');
}]);

请注意,此代码实际上并未经过测试,但应该为您提供如何实现它的大纲。

【讨论】:

  • 抱歉回复晚了,我会试试这个,到家后再告诉你。谢谢。
  • 抱歉,目前无法检查,我现在工作量很大,需要在周末检查。如果一切顺利,我将确保接受它作为答案,并在周末的第一件事中投赞成票。
  • 完美地实施和工作。竖起大拇指,谢谢!
猜你喜欢
  • 2010-10-11
  • 2017-06-29
  • 1970-01-01
  • 2011-03-05
  • 2020-07-06
  • 2019-05-30
  • 1970-01-01
  • 1970-01-01
  • 2015-07-25
相关资源
最近更新 更多