POST方式传值!context.Request.Form["UserID"];获取不到数据context.Request.Params["UserID"]却可以

本文介绍如何使用XUtils框架与C#编写的后台接口进行POST方式的数据传递,并解释了从请求中获取参数的不同方法及其优先级顺序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先,前台用的XUtils框架POST方式传参。后台使用C#编写接口。

context.Request.Params["UserID"]

是从页面的QueryString,Form,Cookies,ServerVariables里面检索名为"UserID"的值。

优先级顺序为:QueryString->Form->Cookies->ServerVariables


context.Request.Form["UserID"];获取不到值是因为Form表单中并没有数据!

前台代码:

RequestParams params = new RequestParams("http://localhost:80/LoginHandler.ashx");
// 加到url里的参数, http://xxxx/s?wd=xUtils 浏览器GET方式
// params.addQueryStringParameter("UserID", userName);
// 添加到请求body体的参数, 只有POST, PUT, PATCH, DELETE请求支持.
params.addBodyParameter("UserID", userName);

后台代码:

 string values = context.Request.Params["UserID"];//可以获取任何方式
 //POST方式传参
 string userid = context.Request.Form["UserID"];
 //GET方式传参
 //string userid = context.Request.QueryString["UserID"]; 


我遇到这个问题是因为前台使用的是GET,我却非认为是POST。最后才发现Form是空的。所以,一定要谨慎!认真!

package com.lc.bailingbird.conn; import android.content.Context; import android.text.TextUtils; import android.util.Log; import com.google.gson.Gson; import com.lc.bailingbird.base.BaseApplication; import com.lc.bailingbird.util.TextUtil; import com.zcx.helper.http.AsyGet; import com.zcx.helper.http.note.HttpFinish; import com.zcx.helper.http.note.HttpServer; import org.json.JSONObject; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import okhttp3.Headers; /** * Created by Administrator on 2017/2/3. */ @HttpFinish(true) @HttpServer(Conn.SERVICE_LT) public class BaseAsyGetLT<T> extends AsyGet<T> { private Context context; public BaseAsyGetLT(BaseAsyCallBack<T> asyCallBack) { super(asyCallBack); context = asyCallBack.context; } /** * 解析响应头数据,会在parser前被调用 * * @param headers */ @Override protected void parserHeaders(Headers headers) { if (!TextUtils.isEmpty(headers.get("token"))) { Log.e("parserHeaders: ", headers.get("token")); // BaseApplication.MYMMKV.encode("token", headers.get("token")); header("token", "63633bd12e294da5b7dcf949ac526d75"); } } @Override protected T parser(JSONObject object) throws Exception { TOAST = object.optString("message"); if (object.optInt("code") == 0) { Type[] types = ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments(); return new Gson().fromJson(object.toString(), types[0]); } else if (object.optInt("code") == -200 || object.optInt("code") == -201) { BaseApplication.MYMMKV.encode("token", ""); BaseApplication.MYMMKV.encode("uid", ""); } return null; } @Override public void execute(boolean isShow) { super.execute(context,isShow); } @Override public void execute() { super.execute(context); } @Override public void execute(Context context, boolean isShow, int type, Object object) { if (!TextUtil.isNull(BaseApplication.MYMMKV.decodeString("token", ""))) { header("token", BaseApplication.MYMMKV.decodeString("token", "")); } super.execute(context, isShow, type, object); } } 在这个里面怎么获取我给后台接口
07-03
import { IBestNavBar } from "@ibestservices/ibest-ui-v2"; import { AxiosResponse } from '@ohos/axios' import { ZcUser } from '../interface/pord' import { ZcUsername, Zcyzm } from '../api/Index' // 导入验证码接口 import log from '@open/log' import prompt from '@system.prompt' @Entry @ComponentV2 export struct Zcuser { router = this.getUIContext().getRouter() @Local count: number = 60 @Local timer: number = 0 @Local username: string = '' @Local password: string = '' @Local mobile: string = '' @Local confirmPassword: string = '' @Local vCode: string = '' @Local list: ZcUser | undefined = undefined @Local passwordVisible: boolean = false @Local confirmPasswordVisible: boolean = false // 注册方法 ZcRegister = async () => { if (!this.validateForm()) return; const regData: ZcUser = { username: this.username, password: this.password, mobile: this.mobile, vCode: this.vCode }; try { const res: AxiosResponse = await ZcUsername(regData); this.list = res.data; log.info('注册成功'); prompt.showToast({ message: '注册成功!', duration: 2000 }); setTimeout(() => { this.router.pushUrl({ url: "pages/Login" }); }, 2000); } catch (error) { log.error('注册失败', error); prompt.showToast({ message: '注册失败: ' + (error.message || '未知错误'), duration: 3000 }); } } // 表单验证 validateForm(): boolean { if (!this.username.trim()) { prompt.showToast({ message: '请输入用户名', duration: 2000 }); return false; } if (!this.mobile.trim()) { prompt.showToast({ message: '请输入手机号', duration: 0 }); return false; } const mobileRegex = /^1[3-9]\d{9}$/; if (!mobileRegex.test(this.mobile)) { prompt.showToast({ message: '请输入正确的手机号', duration: 2000 }); return false; } if (!this.password) { prompt.showToast({ message: '请输入密码', duration: 2000 }); return false; } if (this.password.length < 6) { prompt.showToast({ message: '密码长度至少6位', duration: 2000 }); return false; } if (this.password !== this.confirmPassword) { prompt.showToast({ message: '两次输入的密码不一致', duration: 2000 }); return false; } if (!this.vCode) { prompt.showToast({ message: '请输入验证码', duration: 2000 }); return false; } return true; } // 发送验证码(使用新接口) async sendCode() { if (!this.mobile) { prompt.showToast({ message: '请输入手机号', duration: 2000 }); return; } const mobileRegex = /^1[3-9]\d{9}$/; if (!mobileRegex.test(this.mobile)) { prompt.showToast({ message: '手机号格式错误', duration: 2000 }); return; } if (this.timer) return; try { // 调用验证码接口 const response: AxiosResponse = await Zcyzm(); // 处理接口响应 if (response.data && response.data.vCode) { // 获取6位随机验证码 this.vCode = response.data.vCode; prompt.showToast({ message: '验证码已发送', duration: 2000 }); // 开始倒计时 this.count = 60; this.timer = setInterval(() => { if (this.count > 0) { this.count--; } else { clearInterval(this.timer); this.timer = 0; this.count = 60; } }, 1000); } else { prompt.showToast({ message: '验证码获取失败', duration: 3000 }); } } catch (error) { log.error('验证码发送失败', error); prompt.showToast({ message: '验证码发送失败: ' + (error.message || '请检查网络'), duration: 3000 }); } } @Builder leftBuilder() { Row({ space: 14 }) { Image($rawfile("img/back.png")) .width(16) } } @Builder rightBuilder() { Row({ space: 14 }) { Image($rawfile('img/search.png')) .width(16) } } // 自定义输入框组件 @Builder inputField( icon: Resource, placeholder: string, type: InputType, value: string, onTextChange: (value: string) => void, showEye: boolean = false, isPasswordField: boolean = false ) { Row() { // 左侧图标 Image(icon) .width(24) .height(24) .margin({ left: 12, right: 8 }) // 输入框主体 TextInput({ text: value, placeholder }) .onChange(onTextChange) .type(type) .layoutWeight(1) .height(40) .placeholderColor('#999') .backgroundColor(Color.Transparent) // 密码可见性切换按钮 if (showEye) { Button() { Image($rawfile(isPasswordField ? (this.passwordVisible ? 'img/eye_open.png' : 'img/eye_close.png') : (this.confirmPasswordVisible ? 'img/eye_open.png' : 'img/eye_close.png'))) .width(20) .height(20) } .onClick(() => { if (isPasswordField) { this.passwordVisible = !this.passwordVisible; } else { this.confirmPasswordVisible = !this.confirmPasswordVisible; } }) .backgroundColor(Color.Transparent) .margin({ right: 12 }) } } .width('90%') .height(50) .backgroundColor(Color.White) .borderRadius(8) .margin({ top: 10 }) } build() { Column() { // 导航栏 IBestNavBar({ onLeftClick: () => this.router.back(), title: "乐淘云购", titleFontSize: 30, titleColor: "#fff", navBarBgColor: "#458DF6", leftBuilder: (): void => this.leftBuilder(), isShowRight: true, rightBuilder: (): void => this.rightBuilder() }) // 用户名输入 this.inputField( $rawfile('img/登录.png'), "请输入用户名", InputType.Normal, this.username, (value: string) => { this.username = value } ) // 手机号输入 this.inputField( $rawfile('img/phone.png'), "请输入手机号", InputType.Number, this.mobile, (value: string) => { this.mobile = value } ) // 密码输入 this.inputField( $rawfile('img/密码.png'), "请输入密码", this.passwordVisible ? InputType.Normal : InputType.Password, this.password, (value: string) => { this.password = value }, true, true ) // 确认密码 this.inputField( $rawfile('img/密码.png'), "请确认密码", this.confirmPasswordVisible ? InputType.Normal : InputType.Password, this.confirmPassword, (value: string) => { this.confirmPassword = value }, true, false ) // 验证码区域 Row() { // 验证码输入框 this.inputField( $rawfile('img/code.png'), "请输入验证码", InputType.Number, this.vCode, (value: string) => { this.vCode = value } ) // 发送验证码按钮 Button(this.count === 60 ? '发送验证码' : `重新发送(${this.count})`) .width(120) .height(40) .fontSize(14) .fontColor(Color.White) .backgroundColor(this.count === 60 ? '#458DF6' : '#CCCCCC') // 禁用状态改变颜色 .borderRadius(20) .margin({ right:100 }) .onClick(() => this.sendCode()) .enabled(this.count === 60) // 倒计时期间禁用按钮 } .width('90%') .margin({ top: 10 }) // 注册按钮 Button('立即注册') .width('90%') .height(45) .backgroundColor('#458DF6') .fontColor(Color.White) .fontSize(18) .margin({ top: 30 }) .onClick(() => this.ZcRegister()) // 跳转登录 Flex({ justifyContent: FlexAlign.End }) { Text('立即登录') .onClick(() => this.router.pushUrl({ url: "pages/Login" })) .fontColor("#0A59F7") .margin({ top: 20, right: 30 }) } .width('100%') } .width('100%') .height('100%') .backgroundColor('#f5f5f5') .alignItems(HorizontalAlign.Center) } // 组件销毁时清除定时器 onDestroy() { if (this.timer) { clearInterval(this.timer); this.timer = 0; } } }提供注册接口和验证码接口//注册 export interface ZcUser{ username:string password:string mobile:string vCode:string } //注册验证码 export interface ZcYzm{ vCode:string }//注册用户 export const ZcUsername=(data:ZcUser)=>api.post('user/register',data) //注册验证码 export const Zcyzm=()=>api.get<undefined>('user/vCode')为什么注册账号成功 但是登录页面没有实现账号完成注册
最新发布
07-30
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值