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?
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.
"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
}
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
});
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