首页 > 其他分享 >入门:添加一个支持获取单一资源以及支持POST,PUT和DELETE方法

入门:添加一个支持获取单一资源以及支持POST,PUT和DELETE方法

时间:2022-11-28 14:03:21浏览次数:58  
标签:id application Contact contact PUT POST public DELETE

WCF Web API支持多个宿主环境:自宿主(windows服务或者控制台)和IIS宿主(asp.net webform/mvc)。这个入门文章主要演示在ASP.NET MVC3网站宿主,主要演示如...

WCF Web API支持多个宿主环境:自宿主(windows服务或者控制台)和IIS宿主(asp.net webform/mvc)。这个入门文章主要演示在ASP.NET MVC3网站宿主,主要演示如何在一个Web API上允许更新:

  • 如何检索一个特定项的资源
  • 如何在API上启用HTTP POST, PUT和DELETE方法
  • 如何通过HTML表单发送一个POST到API

这篇入门文章的场景是允许客户端添加、删除和更新系统的联系人。

1、解压启动器代码

要快速开始练习,请到​​这里​​下载代码,下载解压后,打开Start目录下的ContactManager项目。代码和​​入门:构建简单的Web API​​的主要区别是实体代码重构到一个内存 ContactManagerRepository。


public interface IRepository<T>
{
T Find(int id);
IQueryable<T> FindAll();
void Add(T entity);
void Remove(int id);
void Save();
}


using System;
using System.Collections.Generic;
using System.Linq;
using ContactManager.Repositories;

namespace ContactManager.Infrastructure
{
public abstract class InMemoryRepository<T> : IRepository<T> where T:new()
{
protected List<T> entities;
protected int nextId;
static InMemoryRepository<T> instance;
static object lockObject = new object();

public T Find(int id)
{
return entities.SingleOrDefault(e => IsEntityWithId(e, id));
}

public IQueryable<T> FindAll()
{
return entities.AsQueryable();
}

public void Add(T entity)
{
OnAdd(entity, nextId++);
entities.Add(entity);
}

public void Remove(int id)
{
entities.RemoveAll(e => IsEntityWithId(e, id));
}

public void Save()
{
throw new InvalidOperationException();
}

protected abstract bool IsEntityWithId(T contact, int id);

protected abstract void OnAdd(T entity, int newId);
}
}


using ContactManager.Infrastructure;
using ContactManager.Resources;

namespace ContactManager.Repositories
{
public interface IContactRepository : IRepository<Contact>
{
}
}


2、启用检索一个单一的资源并和HttpResponseException协同工作

目前我们的API只支持获取一个联系人集合。另一个通常的场景是通过一个URI返回一个单一的资源,如果找不到相关的资源应该返回一个404状态码。

  • 打开ContactsAp.cs
  • 复制以下方法
[WebGet(UriTemplate="{id}")]

public Contact GetItem(int id)

{

var contact = repository.Find(id);

if (contact == null)

throw new HttpResponseException(HttpStatusCode.NotFound);

return contact;

}
  • 注意GET方法接受一个ID参数映射到{id} uri模板参数。如果你的请求API是​​http://localhost:9000/api/contacts/1​​ 的ID将被设置为1,Web API支持将模板参数自动转换为原生类型int。
  • 如果联系人不存在,就抛出HttpResponseException 并设置状态码
  • 编译并运行(F5)
  • 打开Fiddler并在“Request builder”栏输入地址“http://localhost:9000/api/contacts/1”
  • 拷贝以下内容到header

Accept: application/json

  • 运行执行按钮,Contract 1按json格式返回
HTTP/1.1 200 OK
Server: ASP.NET Development Server/10.0.0.0
Date: Tue, 19 Jul 2011 13:04:26 GMT
X-AspNet-Version: 4.0.30319
Content-Length: 35
Cache-Control: private
Content-Type: application/json; charset=utf-8
Connection: Close

{"ContactId":1,"Name":"Phil Haack"}


3、添加对POST的支持

以下代码是添加一个新的Post方法,添加一个新的Contract

[WebInvoke(UriTemplate = "", Method="POST")]

public Contact Post(Contact contact)

{

repository.Add(contact);

return contact;

}

上面代码里用到了WebInvokeAttribute,对于所有的HTTP GET以外的其他方法,使用此属性。 该方法指定的参数的必须是大写的。

4、以Json格式发送数据

Web Api允许以多个格式发送内容,下面是使用fiddler发送json的POST

Accept: application/json

Content-Type: application/json


  • 拷贝以下内容到“Request Body”
{"Name":"New Person1"}

  • 入门:添加一个支持获取单一资源以及支持POST,PUT和DELETE方法_asp.net

  • 按下“Execute”,返回Json格式的新的Contact ,id为7
HTTP/1.1 200 OK
Server: ASP.NET Development Server/10.0.0.0
Date: Tue, 19 Jul 2011 13:12:57 GMT
X-AspNet-Version: 4.0.30319
Content-Length: 36
Cache-Control: private
Content-Type: application/json; charset=utf-8
Connection: Close

{"ContactId":7,"Name":"New Person1"}
5、以XML格式发送数据
以xml方式发布,需要替换“Request Headers”为以下内容
Content-Type: application/xml

Accept: application/xml
替换“Request Body”为以下内容
<Contact>
<Name>New Person2</Name>
</Contact>
  • 按下“Execute”,然后双击左窗格中的结果,选择“RAW”标签,返回的结果应该是XML,并显示创建了ID为8的一个联系人
HTTP/1.1 200 OK
Server: ASP.NET Development Server/10.0.0.0
Date: Tue, 19 Jul 2011 13:25:50 GMT
X-AspNet-Version: 4.0.30319
Content-Length: 105
Cache-Control: private
Content-Type: application/xml; charset=utf-8
Connection: Close

<?xml version="1.0" encoding="utf-8"?><Contact><ContactId>8</ContactId><Name>New Person2</Name></Contact>
6、从一个简单的HTML表单发送内容
Web API包含从HTML表单的内容发送的直接支持,下面,你添加一个ContactsContrller和相应的View,通过一个HTML表单向Web API发送请求并创建一个Contact
  • 右键单击项目并选择添加Contrller,输入名字为ContactsController 并按下添加
  • 拷贝以下代码到ContactsController
public ActionResult Create()
{
return View();

}
右键Create方法选择 Add-〉New View,并按下”Enter”
打开“Create.cshtml”并把以下代码贴进去
@{

Layout = null;

}

<!DOCTYPE html>

<html>

<head>

<title>Create new Contact</title>

</head>

<body>

<h1>Create new Contact</h1>

<form method="post" action="/api/contacts" id="addContact"

enctype="application/x-www-form-urlencoded">

<table>

<tr>

<td>

Name

</td>

<td>

<input type="text" name="Name" />

</td>

</tr>

<tr>

<td colspan="2" align="center">

<input type="submit" value="Add" />

</td>

</tr>

</table>

</form>

</body>

</html>


7、添加PUT的支持

添加对PUT和DELETE的支持是非常容易的,像POST一样也是使用WebInvoke 制定PUT和DELETE

  • 打开ConactApi.cs把以下代码拷进去
[WebInvoke(UriTemplate ="{id}", Method = "PUT")]
public Contact Put(Contact contact, int id)
{
var existingContact = repository.Find(id);
if (existingContact == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
existingContact.Name = contact.Name;
return existingContact;

}

和DELETE类似,PUT方法在没有找到Contact的情况下,返回一个404状态码

Content-Type: application/json


  • 拷贝以下内容到“Request Body”
{

"Name":"Updated Contact"

}


  • 按下“Execute”
  • 被更新的contact返回,结果如下表明PUT成功
HTTP/1.1 200 OK
Server: ASP.NET Development Server/10.0.0.0
Date: Tue, 19 Jul 2011 13:50:28 GMT
X-AspNet-Version: 4.0.30319
Content-Length: 40
Cache-Control: private
Content-Type: application/json; charset=utf-8
Connection: Close

{"ContactId":1,"Name":"Updated Contact"

8、添加对DELETE的支持

  • 切换到ContactApi.cs并复制以下内容:
[WebInvoke(UriTemplate = "{id}", Method = "DELETE")]

public Contact Delete(int id)

{

var contact = repository.Find(id);

if (contact == null)

{

throw new HttpResponseException(HttpStatusCode.NotFound);

}

repository.Remove(id);

return contact;

}
HTTP/1.1 200 OK
Server: ASP.NET Development Server/10.0.0.0
Date: Tue, 19 Jul 2011 13:55:23 GMT
X-AspNet-Version: 4.0.30319
Content-Length: 40
Cache-Control: private
Content-Type: application/json; charset=utf-8
Connection: Close

{"ContactId":1,"Name":"Updated Contact"}
  • 切换Fiddler的方法为GET,然后执行,返回状态码为404

HTTP/1.1 404 Not Found
Server: ASP.NET Development Server/10.0.0.0
Date: Tue, 19 Jul 2011 13:58:08 GMT
X-AspNet-Version: 4.0.30319
Cache-Control: private
Content-Length: 0
Connection: Close

  • 再次切换方法为DELETE,然后执行,也返回状态码404

总结:在这篇入门文章里我们学习了以下内容:

  • 如何添加检索一个单一的资源
  • 如何设置一个方法返回一个404  处理异常情况下的HTTP 响应。
  • 如何支持POST和URL编码形式。
  • 如何支持PUT和DELETE。

最新版本参考:​​Getting started: Adding support for getting a single resource and supporting POST, PUT and DELETE methods​

 



标签:id,application,Contact,contact,PUT,POST,public,DELETE
From: https://blog.51cto.com/shanyou/5891089

相关文章

  • EF Core | Passing navigation properties in JSON body to API controller as POST r
    EFCore|PassingnavigationpropertiesinJSONbodytoAPIcontrollerasPOSTrequestHere'stheofficialdocsonavoidinggraphcyclesinJSON:learn.micros......
  • element plus input验证
     <template> <el-form  ref="formRef"  :model="numberValidateForm"  label-width="100px"  class="demo-ruleForm"  :rules="rules" ......
  • Python PyDirectInput
    pipinstallpydirectinputimportpydirectinputpydirectinput.moveTo(100,150)#移动鼠标至坐标100,150pydirectinput.click()#点击鼠标左键pydirectinput.click(2......
  • postman的使用
    一、使用介绍1、创建集合  集合可以理解成请求的总和或合集,在Postman中,集合表示将请求进行分组、分模块管理;对含义相近、对功能相近的请求保存到一个集合中,方便后期......
  • 变量、input函数、getpass模块
    一、变量1、声明变量name="ming"print("mynameis",name)上述代码声明了一个变量,变量名为:name,变量name的值为“ming”。2、变量命名规则变量名只能是字母......
  • 用input,output输入,输出5个学生数据记录
    用input,output输入,输出5个学生数据记录思路:学生数据记录--->结构体多个学生数据记录----结构体数组构造函数input(输出),output(输入)//题目:构造input,output函数,......
  • uniapp表单提交 新增POST
    用button的type=submit和form<template><view><viewclass="info"><form@submit='formSubmit'><viewclass="list"><viewclass="item">......
  • vmware workstation使用串中管道与putty交互
    添加串口,使用命令的管道\\.\pipe\com_1先启动vm虚机,然后打开putty需要在vmware虚机的grub中设置console=ttyS0,115200n8......
  • lightdb/postgresql中的事务回卷原理解析及避免
    在pg中,由于事务id采用32位实现,所以是采用循环复用的,如下:  虽然最大支持4billion个事务(32位无符号数,xid最大可以到40亿),但是新老事务相差2billion是上限,当达......
  • Java: User Input (Scanner)
    The Scanner classisusedtogetuserinput,anditisfoundinthe java.util package.Tousethe Scanner class,createanobjectoftheclassandusean......