我已被分配到想出一個接收和發佈數據的Web服務。但是,我對此很新,甚至在查看了多個示例並試圖關注它們之後,我也有一些難以理解的地方。使用C#的restful Web服務
引用的例子:
,我已經給出作爲用於模型和控制器的參考代碼如下:
模型
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace Webservice.Models.ApiModels {
public class SecondlyReading {
[Key]
public int Id { get; set; }
[Required]
public int Name { get; set; }
[Required]
public string TimeStamp { get; set; }
[Required]
public string Date { get; set; }
[Required]
}
}
控制器
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web.Http;
using SmartDBWeb.Data;
using Microsoft.AspNetCore.Authorization;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using SmartDBWeb.Models.ApiModels;
using Microsoft.EntityFrameworkCore;
namespace Webservice.Controllers.Api {
[Route("api/[controller]")]
[Authorize]
public class WebserviceController : Controller {
private ApplicationDbContext _context;
public WebserviceController(ApplicationDbContext context) {
_context = context;
}
// GET: api/Webservice
[HttpGet]
public IEnumerable<Webservice> GetSecondlyReadings() {
return _context.Webservice.ToList();
}
// GET api/Webservice/id
[HttpGet("{id}")]
public async Task<IActionResult> GetWebservice(int id) {
var reading = await _context.Webservice.SingleOrDefaultAsync(c => c.Id == id);
if (reading == null) {
return NotFound();
}
return Ok(reading);
}
[HttpPost]
public IActionResult PostWebservice([FromBody]List<Webservice> Readings) {
if (!ModelState.IsValid) {
return BadRequest();
}
foreach (Webservice reading in Readings) {
_context.Webservice.Add(reading);
}
_context.SaveChanges();
return CreatedAtAction("GetWebservice", new { id = Readings[0].Id }, Readings[0]);
}
}
}
我的主要問題是如何使用上面的代碼的一般工作。我發現的(可能不正確)是,模型是數據本身,控制器將模型和視圖連接在一起。
不要忘了「處置」這方面。 –