https://blog.csdn.net/QiGary/article/details/113979877

在做后台api接口时,常常涉及到Http方法访问问题,其中最基础也是最核心的就是传参问题。在基于C#的webapi项目中,其传参有两种实现方式,一种是使用[FromBody]和[FromUri]作为Http接口函数形参前缀传参,另一种是将函数的形参设置为空,使用System.Web.Http命名空间下的【HttpContext.Current.Request】获取。

第一种,使用[FromBody]和[FromUri]作为Http接口函数形参前缀传参

eg1:在url中传参访问,即后端使用[FromUri]

[Route("ParamsGetTest"), HttpGet]
public string ParamsGetTest([FromUri]string param1,[FromUri]string param2)
{
string result = "none";
return result;
}

[Route("ParamsPostTest"), HttpPost]
public string ParamsPostTest([FromUri]string param1, [FromUri]string param2)
{
string result = "none";
return result;
}

[Route("ParamsPostTest"), HttpPost]
public string ParamsPostTest()
{
string param1= HttpContext.Current.Request.Params["param1"].Trim();
string param2= HttpContext.Current.Request.Params["param2"].Trim();
return "ok";
}
此种接口允许url传参,其中,参数名【param1】和【param2】要与接口一致。访问形式如:https://localhost:44358/Test/ParamsPostTest?param1=admin&param2=admin

在postman测试时,直接在【Params】标签页传参即可。

eg2:在Body中传参访问,即后端使用[FromBody]

//JObject 传值(推荐使用,可以转化为任意实体对象)
[Route("ParamsPostTest"), HttpPost]
public string ParamsPostTest([FromBody]JObject obj)
{
//obj任意名称
RequestBody result = null;
if (obj != null)
{
result = obj.ToObject<RequestBody>();
}
return JsonConvert.SerializeObject(result);
}

//具体实际对象直接传值 T=RequestBody
[Route("ParamsPostTest"), HttpPost]
public string ParamsPostTest([FromBody]RequestBody obj)
{
//obj任意名称
return JsonConvert.SerializeObject(obj);
}

//字符串传值 可为json串
[Route("ParamsPostTest"), HttpPost]
public string ParamsPostTest([FromBody]string obj)
{
//obj任意名称
return JsonConvert.SerializeObject(obj);
}

get方法使用与Post一致,其中,参数名【obj】任意。

在postman测试时,在【Body】标签页【x-www-form-urlencoded】和【raw】选项内,均可实现访问测试,推荐使用【raw】选项测试。

————————————————
版权声明:本文为CSDN博主「QiGary」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/QiGary/article/details/113979877

在WebAPI中,请求主体(HttpContent)只能被读取一次,不被缓存,只能向前读取的流。

举例子说明:

1. 请求地址:/?id=123&name=bob

服务端方法: void Action(int id, string name) // 所有参数都是简单类型,因而都将来自url

2. 请求地址:/?id=123&name=bob

服务端方法: void Action([FromUri] int id, [FromUri] string name) // 同上

void Action([FromBody] string name); //[FormBody]特性显示标明读取整个body为一个字符串作为参数

3. 请求地址: /?id=123

类定义:

public class Customer {   // 定义的一个复杂对象类型 
  public string Name { get; set; } 
  public int Age { get; set; } 
}

服务端方法: void Action(int id, Customer c) // 参数id从query string中读取,参数c是一个复杂Customer对象类戏,通过formatter从body中读取

服务端方法: void Action(Customer c1, Customer c2) // 出错!多个参数都是复杂类型,都试图从body中读取,而body只能被读取一次

服务端方法: void Action([FromUri] Customer c1, Customer c2) // 可以!不同于上面的action,复杂类型c1将从url中读取,c2将从body中读取

4.ModelBinder方式:

void Action([ModelBinder(MyCustomBinder)] SomeType c) // 标示使用特定的model binder来解析参数

[ModelBinder(MyCustomBinder)] public class SomeType { } // 通过给特定类型SomeType声明标注[ModelBidner(MyCustomBinder)]特性使得所有SomeType类型参数应用此规则

void Action(SomeType c) // 由于c的类型为SomeType,因而应用SomeType上的特性决定其采用model binding

总结:

1. 默认简单参数都通过URL参数方式传递,例外:

1.1 如果路由中包含了Id参数,则id参数通过路由方式传递;

1.2 如果参数被标记为[FromBody],则可以该参数可以为简单参数,客户端通过POST方式传递:$.ajax(url, '=value'),或者$.ajax({url: url, data: {'': 'value'}});

2. 默认复杂参数(自定义实体类)都通过POST方式传递,例外:

2.1 如果参数值被标记为[FromUri], 则该参数可以为复杂参数;

3. 被标记为[FromBody]的参数只允许出现一次, 被标记为[FromUri]的参数可以出现多次,如果被标记为[FromUri]的参数是简单参数,该标记可以去掉。

 
 
 
posted on 2014-08-11 09:12 Juvy 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/Juvy/p/3903974.html

 

webapi fromurl frombody的更多相关文章

  1. webapi frombody fromuri的参数绑定规则

    在WebAPI中,请求主体(HttpContent)只能被读取一次,不被缓存,只能向前读取的流. 举例子说明: 1. 请求地址:/?id=123&name=bob 服务端方法: void Ac ...

  2. asp.net webapi [FromBody]string 获取不到ajax post的数据的解决方法

    webapi中如下([FromBody]string jsonData: public async Task<ResItem> Post([FromBody]string jsonData ...

  3. WebAPI Post方法接收的FromBody一直为null

    // POST api/getjson public string PostTest([FromBody]string value) { return "Got it!"; } 初 ...

  4. [FromBody]与[FromUrl]

    我们都知道,前台请求后台控制的方法有get方法和post方法两种, get:只支持ulr传数据,不管你是手动把参数拼接在Url里面还是写在data里面,只要是用get方法,都会自动绑定到url里面的形 ...

  5. webApi之FromUri和FromBody区别

    public Link GetLink([FromUri] FileRequest fileRequest) { if (ModelState.IsValid) { var xml = WebConf ...

  6. 问题:调用 ASP.Net Core WebAPI的HTTP POST方法时,从 [FromBody] 中读取的 MongoDB GeoJsonObjectModel成员总是null

    问题描述: POST/PUT to ASP.Net Core with [FromBody] to a MongoDB GeoJsonObjectModel member is always null ...

  7. 关于ASP.NET中WEBAPI中POST请求中FromBody修饰的string类型的参数服务器端获取不到值FromBody空值的简单解决方法

    其实解决办法很简单,就是POST请求的时候,来自实体的参数,content-type:application/x-www-form-urlencoded情况下,是默认按照键值对来解析的,比如param ...

  8. .Net WebApi 中的 FromBody FromForm FromQuery FromHeader FromRoute

    在日常后端Api开发中,我们跟前端的沟通中,通常需要协商好入参的数据类型,和参数是通过什么方式存在于请求中的,是表单(form).请求体(body).地址栏参数(query).还是说通过请求头(hea ...

  9. 第二节:如何正确使用WebApi和使用过程中的一些坑

    一. 基本调用规则 1. 前提 WebApi的默认路由规则为:routeTemplate: "api/{controller}/{id}", 下面为我们统一将它改为 routeTe ...

  10. C#进阶之WebAPI(二)

    今天学习一下:WebAPI如何使用呢? 首先我们打开vs新建一个WebAPI项目,可以看到一共有这些文件夹目录 首先了解一下这些文件夹/文件的意义(按照程序启动的流程,相关的配置项就不说了), Glo ...

随机推荐

  1. Redis 源码解读之 Rehash 的调用时机

    Redis 源码解读之 Rehash 的调用时机 背景和问题 本文想要解决的问题 什么时机触发 Rehash 操作? 什么时机实际执行 Rehash 函数? 结论 什么时机触发 Rehash 操作? ...

  2. Integer使用==比较的问题

    Integer使用==比较的问题 new一个对象 public Integer(int value) { this.value = value; } 自动装箱 public static Intege ...

  3. 集成RocketChat至现有的.Net项目中,为ChatGPT铺路

    @ 目录 前言 项目搭建 后端 前端 代理账号 鉴权方式介绍 登录校验模块 前端鉴权方式 后端鉴权方式 登录委托 使用登录委托 处理聊天消息 前端鉴权方式 后端校验方式 项目地址 前言 今天我们来聊一 ...

  4. 96、nacos大量日志

    问题描述:access 日志大量打印,相关 Issue 点击这里.主要表现是: {nacos.home}/logs/access_log.2019-xx-xx.log类似格式文件名的日志大量打印,而且 ...

  5. 360 quake 网络空间测绘引擎真的很不错

    最近通过使用360 quake搜索引擎,发现真的能够比较准确的找到数据,对比fofa,shodan这种免费用户使用体验真的很好,搜到的数据很是全面,但是搜索的资产是国内的ip时会做脱敏处理.有时间大家 ...

  6. 【C学习笔记】day5-2 写代码可以在整型有序数组中查找想要的数字, 找到了返回下标,找不到返回-1.(折半查找)

    #include <stdio.h> #include <stdlib.h> int find(int s) { int n = 0; scanf_s("%d&quo ...

  7. react+Native使用typeScript

    1.为什么使用typeScript? typeScript是JavaScript的超集 typeScript在编译期间就可以将错误抛出 增强代码的可阅读性和可维护性 2.案例的功能逻辑 切换职业 选择 ...

  8. vue 使用路由component: () =>import (‘ ‘)报错解决办法

    今天帮朋友调代码的时候,在人家的mac上面,项目没有任何错误,到我这里就出现 component: () =>import (' ')加载路由错误. 发现是import处报错, import 属 ...

  9. js提取字符串开头公共部分

    需求: 编写一个函数来查找字符串数组中的最长公共前缀. 如果不存在公共前缀,返回空字符串 "". 思路:记录数组中第一个字符串的每个字符,依次判断数组中的每个字符串是否都有这个字符 ...

  10. nfs-client-provisioner 利用NFS动态提供Kubernetes后端存储卷

    nfs-client-provisioner 利用NFS动态提供Kubernetes后端存储卷     一.选一个节点安装nfsserver 服务   yum install nfs-common n ...