它是一個傳統的 ASP.NET MVC 控制器。它只是負責處理站點的HTML頁,跟Web API沒有直接關係。
手動添加一個API控制器
選擇包含空讀/寫操作的API控制器,然後添加。
添加完後可看到空白的控制器代碼,然後根據需要補充邏輯需求。
例:
using MFirstWAPI.Models;
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Text;
using System.Web.Http;
using System.Web.Script.Serialization;
namespace MFirstWAPI.Controllers
{
public class UsersController : ApiController
{
// GET api/values
public IEnumerable<Users> Get()
{
List<Users> listUser = new List<Users>();
MySqlConnection mysql = getMySqlConnection();
MySqlCommand mySqlCommand = getSqlCommand("select * from user",mysql);
mysql.Open();
MySqlDataReader reader = mySqlCommand.ExecuteReader();
try
{
while (reader.Read())
{
if (reader.HasRows)
{
Users user = new Users();
user.UserID = reader.GetInt32("ID");
user.UserName = reader.GetString("username");
user.UserEmail = reader.GetString("useremail");
listUser.Add(user);
}
}
}
catch
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
finally
{
mysql.Close();
}
return listUser;
}
// GET api/Users/5
public Users GetUserByID(int id)
{
Users user = new Users();
MySqlConnection mysql = getMySqlConnection();
MySqlCommand mySqlCommand = getSqlCommand("select * from USER where ID=" + id, mysql);
mysql.Open();
MySqlDataReader reader = mySqlCommand.ExecuteReader();
try
{
while (reader.Read())
{
if (reader.HasRows)
{
user.UserID = reader.GetInt32(0);
user.UserName = reader.GetString(1);
user.UserEmail = reader.GetString(2);
}
}
reader.Close();
}
catch
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
finally
{
reader.Close();
}
return user;
}
//GET api/Users/?username=xx
public IEnumerable<Users> GetUserByName(string userName)
{
List<Users> listuser = new List<Users>();
MySqlConnection msql = getMySqlConnection();
MySqlCommand mySqlCommand = getSqlCommand("select * from USER where username like'%" + userName+"%'",msql);
msql.Open();
MySqlDataReader reader = mySqlCommand.ExecuteReader();
try
{
while (reader.Read())
{
if (reader.HasRows)
{
Users user = new Users();
user.UserID = reader.GetInt32("ID");
user.UserName = reader.GetString("USERNAME");
user.UserEmail = reader.GetString("USEREMAIL");
listuser.Add(user);
}
}
reader.Close();
}
catch
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
finally
{
reader.Close();
}
return listuser;
}
// POST api/values
public void Post([FromBody]string value)
{
}
// PUT api/values/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
public void Delete(int id)
{
}
private static MySqlConnection getMySqlConnection()
{
MySqlConnection mysql = new MySqlConnection(ConfigurationManager.ConnectionStrings["MySqlConnection"].ConnectionString);
return mysql;
}
public static MySqlCommand getSqlCommand(String sql, MySqlConnection mysql)
{
MySqlCommand mySqlCommand = new MySqlCommand(sql, mysql);
return mySqlCommand;
}
}
}
此處代碼,主要補充了Get方法的邏輯。數據從mysql數據庫中獲取。例中MySql對應user表中數據如下
獲取數據共寫了三個get方法,第一個是獲取所有user數據,
第二個根據Users 的ID獲取對應Users,第三個根據UserName獲取Users。爲了能夠通過MySql獲取數據,需要在Web.config的<connectionStrings>節點中添加
<add name="" providerName="System.Data.SqlClient" connectionString=""/>
name爲connectionString對應名稱,connectionString中爲連接mysql的配置
代碼中通過ConfigurationManager.ConnectionStrings["name"].ConnectionString獲取mysql配置。
完成代碼編寫後,即可對進行代碼測試。如果需要部署到IIS,則需要發佈網站,然後配置IIS,需要注意的是IIS應用程序池需要
.net FramWork版本爲4.0。否則部署不成功。
Chorm通過 IIS獲取數據如下:
四、修改返回數據JSON非XML
如果不修改返回數據類型,chrome中默認返回的數據並不是以上圖片所示數據格式,而是XML類型,IE下返回的數據位JSON格式。
那麼如何修改只返回JSON而屏蔽掉,百度後會有很多實例,本例使用的是通過使用自定義的只返回Json Result的content negotiation代替Web Api中默認的content negotiation。Conneg通過實現IContentNegotiator的Negotiator方法實現擴展。Negotiator方法返回ContentNegotiationResult(它包裝了你選擇的headers和formatter)。
下面的方法通過傳遞一個JsonMediaTypeFormatter給自定義的conneg negotiator,讓它一直返回applicaton/json 的content-type以及JsonMediaTypeFormatter。這種方法避免了每次請求都要重新創建一次formatter。
方法如下:
public class JsonContentNegotiator : IContentNegotiator
{
private readonly JsonMediaTypeFormatter _jsonFormatter;
public JsonContentNegotiator(JsonMediaTypeFormatter formatter)
{
_jsonFormatter = formatter;
}
public ContentNegotiationResult Negotiate(Type type, HttpRequestMessage request, IEnumerable<MediaTypeFormatter> formatters)
{
var result = new ContentNegotiationResult(_jsonFormatter, new MediaTypeHeaderValue("application/json"));
return result;
}
}
然後接下來,需要在HttpConfiguration實例上註冊新的實現機制,在App_Start下找到WebApiConfig.cs添加代碼,添加完後代碼如下
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var jsonFormatter = new JsonMediaTypeFormatter();
config.Services.Replace(typeof(IContentNegotiator), new MFirstWAPI.Controllers.UsersController.JsonContentNegotiator(jsonFormatter));
}
}
紅色部分爲新加代碼
最後編譯發佈,通過Chrome瀏覽器獲取數據爲JSON格式了。