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

Time:11-09

I have coded in the StartUp.cs the following code for calling my API.

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

But when I want to call the ActionResult by using an Ajax-call, he can't find the API.

    alert(apiUrl);

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

So I have written this variable in a js-file.

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

I want to know if it is possible to write it dynamically. If you declare it in the startup, you don't have to declare it twice?

CodePudding user response:

If you need to use urls in ajax or httpclient, I usually do it this way, but it takes several steps to get a string from appsettings.

  1. Create AppUrl section in appsettings.json
"AppUrl": {
    "DevUrl": "http//..",
    "ProductUrl": "http//..",
     .... another urls if needed
   
},

2.Create class for this section

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

        ....another urls
   }
  1. configure settings in startup
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. now you can use them like this
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;
               ...
           }
        }
}

you can then use urls as hidden fields.

or you can get urls from model in javascript directly:

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

Or if you need the urls in many places, it can make sense to create a special service that you can inject directly in the views you need

CodePudding user response:

i don't know i catched the problem or not but I think apiUrl is not mandatory before "Controller/Action" for ajax Url propert. which means that is enough ..

    $.ajax({
            url:'/MyApiProcesses/GetSomething',
            type: 'POST',
  • Related