我在 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';
我想知道是否可以動態撰寫它。如果在啟動時宣告,就不用宣告兩次了?
uj5u.com熱心網友回復:
如果你需要在ajax或httpclient中使用url,我通常是這樣操作的,但是從appsettings中獲取字串需要幾個步驟。
- 在 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
}
- 在啟動時配置設定
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;
...
}
}
}
然后您可以使用 url 作為隱藏欄位。
或者您可以直接從javascript中的模型獲取網址:
var devUrl = @Html.Raw(Json.Encode(@Model.DevUrl));
.....
或者,如果您在很多地方都需要 url,那么創建一個可以直接注入到您需要的視圖中的特殊服務是有意義的
uj5u.com熱心網友回復:
我不知道我是否發現了問題,但我認為 apiUrl 在 ajax Url 屬性的“控制器/操作”之前不是強制性的。這意味著這就足夠了..
$.ajax({
url:'/MyApiProcesses/GetSomething',
type: 'POST',
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/353616.html
標籤:javascript C# 阿贾克斯 接口 模型视图控制器
上一篇:Postman請求-如何根據API檔案從端點獲取資料
下一篇:KucoinAPI錢包余額
