1. 程式人生 > 其它 >uniapp跨域呼叫ASP.NET Core Web API

uniapp跨域呼叫ASP.NET Core Web API

去年做過一個疫情登記的程式,系統分為3塊:

1. 使用uniapp開發的H5前端頁面,功能很簡單就是上傳圖片和提交資訊。

2. 使用ASP.NET Core Web API開發的服務端介面

3. 使用BootstrapBlazor開發的後臺管理系統。 

 

一、Web API跨域支援

因為瀏覽器有CROS(跨域資源共享)的問題,所以我們開發的Web API介面需要新增跨域功能。

1. 在Startup.cs的ConfigureServices方法裡新增如下程式碼:

 //支援跨域
services.AddCors(options =>
{
        options.AddPolicy("any", builder =>
        {
            builder
            .AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader();
            //.AllowCredentials();  //指定處理cookie
        });
});

any為策略名稱,可以自己起名。

2. 在Startup.cs的Configure方法裡新增如下程式碼:

if (env.IsDevelopment())
{
    app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseStaticFiles();
app.UseCors("any"); 
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers().RequireCors("any");
});

注意,app.UseCors("any"); 必須放入app.UseRouting和app.UseEndpoints方法之間。

3. 在Controller裡啟用跨域,新增[EnableCors("any")],如下所示:

[EnableCors("any")]
[Route("api/[controller]")]
[ApiController]
public class RegInfoController : ControllerBase
{
    //省略控制器程式碼
}

這樣將該Web API釋出到IIS,就可以支援跨域訪問該介面服務了。

 

二、uniapp跨域訪問

 這裡我主要用到uniapp的兩個方法,uploadFile和request方法。具體的用法可以參考官方文件:https://uniapp.dcloud.io/api/request/request.html

 。

a. uploadFile示例:

uni.chooseImage({
	sourceType: sourceType[this.sourceTypeIndex],
	sizeType: sizeType[this.sizeTypeIndex],
	count4: this.imageList4.length + this.count4[this.countIndex4] > 1 ? 1 - this.imageList4.length : this.count4[this.countIndex4],
	success: (res) => {
        var size = res.tempFiles[0].size;
		console.log(size);

		if (size > 2097152) {
			uni.showToast({
				title: "圖片大小不能超過2M",
				icon: 'none',
				duration: 1000,
				mask: true
			});
			return
		}
						
		if(size < 100000){
			uni.showToast({
				title: "圖片大小不能少於100K",
				icon: 'none',
				duration: 1000,
				mask: true
			});
			return
		}

		this.imageList4 = this.imageList4.concat(res.tempFilePaths);
		uni.showLoading({
			title: '圖片上傳中'
		});
		var imageSrc = res.tempFilePaths[0]
		uni.uploadFile({
			url: 'http://ip:埠/api/RegInfo/UploadImage', 
			formData: {
				'd': 'Images4' //傳參到Web API
			},
			filePath: imageSrc,
			fileType: 'image',
			name: 'data',
			success: (res) => {
				console.log('uploadImage success, res is:', res.data)
				this.image4 = res.data
				uni.hideLoading();
				uni.showToast({
					title: '上傳成功',
					icon: 'success',
					duration: 1000,
					mask: true
				})
			},
			fail: (err) => {
				console.log('uploadImage fail', err);
				uni.showModal({
					content: err.errMsg,
					showCancel: false
				});
			}
		});
	},
	fail: (err) => {
		console.log("err: ", err);
		// #ifdef APP-PLUS
		if (err['code'] && err.code !== 0 && this.sourceTypeIndex === 2) {
			this.checkPermission(err.code);
		}
		// #endif
		// #ifdef MP
		if (err.errMsg.indexOf('cancel') !== '-1') {
			return;
		}
		uni.getSetting({
			success: (res) => {
				let authStatus = false;
				switch (this.sourceTypeIndex) {
					case 0:
						authStatus = res.authSetting['scope.camera'];
						break;
					case 1:
						authStatus = res.authSetting['scope.album'];
						break;
					case 2:
						authStatus = res.authSetting['scope.album'] && res.authSetting['scope.camera'];
						break;
					default:
						break;
				}
				if (!authStatus) {
					uni.showModal({
						title: '授權失敗',
						content: 'Hello uni-app需要從您的相機或相簿獲取圖片,請在設定介面開啟相關許可權',
						success: (res) => {
							if (res.confirm) {
								uni.openSetting()
							}
						}
					})
				}
			}
		})
		// #endif
	}
})

後臺控制器方法接收上傳的圖片程式碼片段:

var file = Request.Form.Files[0];
byte[] bytes = new byte[file.OpenReadStream().Length];
file.OpenReadStream().Read(bytes, 0, bytes.Length);

MemoryStream ms = new MemoryStream(bytes);
Bitmap bitmap = new Bitmap(ms);

string d = Request.Form["d"]; //型別對應不同的目錄
string path = Directory.GetCurrentDirectory() + "/Images/" + d + "/" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".jpg";
bitmap.Save(path);
ms.Close();
bitmap.Dispose();

b. request示例:

uni.request({
    url: 'https://xxx.xxx.xxx.xxx:8098/api/RegInfo/AddRegInfo', //僅為示例,並非真實介面地址,前面的xxx為伺服器ip或者改成域名。
    data: {
        text1: 'text1',
        text2: 'text2'
    },
    success: (res) => {
        console.log(res.data);
        this.text = 'request success';
    }
});

這裡的引數data,裡面可以封裝成一個json物件傳給Web API後臺,後臺方法引數為物件,該物件的屬性跟text1,text2對應即可,可自由設定這裡僅作演示。

 

三、釋出到IIS的一些問題

1. .net core HTTP Error 500.31-Failed to load ASP.NET Core runtime錯誤

在伺服器執行cmd,輸入dotnet --version,檢視.net core版本號。在釋出Web API設定目標框架的時候,選擇匹配這個版本號的.NET Core版本即可。

2. .net core HTTP Error 500.30 -ANCM In-Process Handler Load Failure

a. 檢查釋出選項設定

b. 找到釋出過的Web API裡的web.config檔案並將 hostingModel="InProcess" 配置結點刪除

c. 在IIS該應用的應用程式池中,開啟啟用32位應用程式

d. 快速故障防護是否關閉

 

 

參考資料:

1. uniapp官方首頁: https://uniapp.dcloud.io/

2. bootstrapblazor官方首頁:https://www.blazor.zone/

3. 微軟官方Web API教程:https://docs.microsoft.com/zh-cn/aspnet/core/tutorials/first-web-api?view=aspnetcore-6.0&tabs=visual-studio