C# Asp.NETWebAPI来获取特定项的getails
大家好,我是C# Asp.NETWebAPI来获取特定项的getails,c#,asp.net-web-api,C#,Asp.net Web Api,大家好,我是Asp.NETWebAPI新手,我想了解一个特定项目的详细信息,其中项目代码必须以邮递员的标题或json格式传递 我是这样做的 public List<Product> GetByCode(string ItemCode) { using (var context = new DBContext()) { var getItem = (from s in context.objProduct where (s.ItemCode == Ite
Asp.NETWebAPI
新手,我想了解一个特定项目的详细信息,其中项目代码必须以邮递员的标题或json格式传递
我是这样做的
public List<Product> GetByCode(string ItemCode)
{
using (var context = new DBContext())
{
var getItem = (from s in context.objProduct where (s.ItemCode == ItemCode) select s).ToList();
if (getItem!=null )
{
return getItem;
}
else
{
return null;
}
}
}
public List GetByCode(string ItemCode)
{
使用(var context=new DBContext())
{
var getItem=(来自context.objProduct中的s,其中(s.ItemCode==ItemCode)选择s.ToList();
if(getItem!=null)
{
返回项目;
}
其他的
{
返回null;
}
}
}
如果我通过查询字符串这样做
localhost:50787/API/Product/GetByCode?ItemCod=3F-47-AB-84-9F-EB-D6-6B-9C-62-CC-85-98-4D-28-6B
因为它工作得很好。
但我希望它必须通过JSON或带有键和值的头来传递
请帮帮我。你可以这样做 为您的模型创建一个类:
public class Item
{
public string Code {get;set;}
}
并按如下方式更改控制器:
[HttpPost]
public List<Product> GetByCode([FromBody]Item item)
{
using (var context = new DBContext())
{
var getItem = (from s in context.objProduct where (s.ItemCode == item.Code) select s).ToList();
if (getItem!=null )
{
return getItem;
}
else
{
return null;
}
}
}
[HttpPost]
公共列表GetByCode([FromBody]项)
{
使用(var context=new DBContext())
{
var getItem=(来自context.objProduct中的s,其中(s.ItemCode==item.Code)选择s.ToList();
if(getItem!=null)
{
返回项目;
}
其他的
{
返回null;
}
}
}
希望有帮助:)首先,您需要将请求发布到您的终点。为此,您需要使用
[HttpPost]
属性编辑您的操作
[HttpPost]
public List<Product> GetByCode(string ItemCode) {...}
会有用的,但你说
但我希望它必须通过JSON或带有键和值的头来传递
通过标题传递它将需要您做更多的工作
以这个请求为例,代码以自定义头发送
POST localhost:50787/API/Product/GetByCode HTTP/1.1
User-Agent: Fiddler
Host: localhost:50787
ItemCode: 3F-47-AB-84-9F-EB-D6-6B-9C-62-CC-85-98-4D-28-6B
您必须自定义API以查找特定的头键,然后将其映射到预期的操作参数。比你真正需要做的更多的工作
要将其作为JSON正文发送,并使其仍然使用简单类型调用您的操作,您需要更新您的操作以了解如何处理请求
[HttpPost]
public List<Product> GetByCode([FromBody]string ItemCode) {...}
来源:您希望它成为POST请求吗?是的,它必须以json格式返回我使用[HttpPost]作为方法装饰,并在发出请求时将内容类型头设置为application/json
[HttpPost]
public List<Product> GetByCode([FromBody]string ItemCode) {...}
POST localhost:50787/API/Product/GetByCode HTTP/1.1
User-Agent: Fiddler
Host: localhost:50787
Content-Type: application/json
Content-Length: 49
"3F-47-AB-84-9F-EB-D6-6B-9C-62-CC-85-98-4D-28-6B"