【问题标题】:How to dynamically call an ActionResult in your API by using an Ajax-call?如何使用 Ajax 调用在 API 中动态调用 ActionResult?
【发布时间】:2021-12-21 07:20:32
【问题描述】:

我在 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-call调用ActionResult时,他找不到API。

    alert(apiUrl);

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

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

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

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

【问题讨论】:

    标签: javascript c# ajax api model-view-controller


    【解决方案1】:

    如果需要在ajax或者httpclient中使用url,我一般都是这样,但是从appsettings中获取字符串需要几个步骤。

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

    2.为本节创建类

     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中从模型中获取url:

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

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

    【讨论】:

    • 谢谢它工作正常。
    猜你喜欢
    • 2016-04-13
    • 1970-01-01
    • 1970-01-01
    • 2014-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-03
    相关资源
    最近更新 更多