如何使用 Ajax 调用在 API 中动态调用 ActionResult?

How to dynamically call an ActionResult in your API by using an Ajax-call?

我在 StartUp.cs 中编写了以下代码来调用我的 API。

            services.AddHttpClient("MyApi", c =>
            {
#if DEBUG
                c.BaseAddress = new Uri("https://localhost:12345");
#else
                c.BaseAddress = new Uri("https://myApi.com");
#endif

但是当我想用Ajax调用ActionResult时,他找不到API。

    alert(apiUrl);

    $.ajax({
        url: apiUrl + '/MyApiProcesses/GetSomething',
        type: 'POST',

所以我把这个变量写在了一个js文件中。

var apiUrl = 'https://localhost:12345';
//var apiUrl = 'https://myApi.com';

我想知道是否可以动态编写。如果在启动时声明,就不用声明两次了?

如果你需要在ajax或httpclient中使用url,我通常是这样做的,但是从appsettings中获取一个字符串需要几个步骤。

  1. 在 appsettings.json
  2. 中创建 AppUrl 部分
"AppUrl": {
    "DevUrl": "http//..",
    "ProductUrl": "http//..",
     .... another urls if needed
   
},
本节

2.Create class

 public class AppUrlSettings
  {
        public string DevUrl{ get; set; }
        public string ProdUrl{ get; set; }

        ....another urls
   }
  1. 在启动时配置设置
var appUrlSection=Configuration.GetSection("AppUrl");

services.Configure<AppUrlSettings>(appUrlSection);

var urls = appUrlSection.Get<AppUrlSettings>();

services.AddHttpClient("MyApi", c =>
 {
#if DEBUG
                c.BaseAddress = new Uri(urls.DevUrl);
#else
                c.BaseAddress = new Uri(urls.ProdUrl;
#endif
});
  1. 现在您可以像这样使用它们了
public class MyController:Controller
    {
        private readonly IOptions<AppUrlSettings> _appUrls;

        public MyController (IOptions<AppUrlSettings> appUrls)
        {
            _appUrls = appUrls;
        }

        public  IActionResult MyAction()
        {
           var model= new Model
           {
            DevUrl=_appUrls.Value.DevUrl;
               ...
           }
        }
}

然后您可以将 url 用作隐藏字段。

或者您可以直接从 javascript 中的模型获取网址:

var devUrl = @Html.Raw(Json.Encode(@Model.DevUrl));
.....

或者如果你在很多地方都需要 url,创建一个可以直接注入你需要的视图的特殊服务是有意义的