1. 程式人生 > WINDOWS開發 >ASP.NET WebApi專案框架搭建(一):建立專案

ASP.NET WebApi專案框架搭建(一):建立專案

一、WebApi簡介

ASP.NET Web API是一個框架,可以輕鬆構建HTTP服務,覆蓋廣泛的客戶端,包括瀏覽器和移動裝置。ASP.NET Web API是在.NET Framework上構建RESTful應用程式的理想平臺。其中,RESTful屬於一種設計風格,REST中的GET,POST,PUT DELETE來進行資料的增刪改查,如果開發人員的應用程式符合RESTful原則,則它的服務稱為"RESTful風格應用服務"。

二、建立WebApi專案

1.開啟VS2019,新建專案,選擇ASP.NET Web 應用程式(.NET Framework),框架選擇.NET Framework4.5,如下圖所示。

技術分享圖片

2.選擇空專案,勾選Web API選項,去掉https支援,如下圖所示

技術分享圖片

3.Controllers資料夾下新建一個控制器“IndexController”

技術分享圖片

4.Model資料夾下新建一個Person實體類

    public class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Sex { get; set; }
        public int Age { get; set
; } }

5.在App_Start資料夾下的WebApiConfig定義了我們的路由規則

技術分享圖片

6.在我們的控制器裡寫一個Get請求方法,

 Person[] person = new Person[]
       {
            new Person { Id = 1,Name = "張三",Sex = "",Age = 18 },new Person { Id = 1,Name = "李四",Sex = "",Name = "王二",Age = 22 },Name = "麻子",Age = 23 },};

        [HttpGet]
        public
IHttpActionResult index() { return Ok(person); }

7.執行專案瀏覽器地址後面加上/api/index效果如下:

技術分享圖片

8.如果我們再寫一個get請求,執行後再次輸入http://localhost:xxx/api/index。

技術分享圖片

會發現,瀏覽器報錯了,那是因為程式不知道你請求的是哪個方法。

技術分享圖片

WebAPI可以通過[Route]和[RoutePrefix]來自定義路由,[RoutePrefix]作用於Controller,[Route]作用於Action。我們在控制加上[RoutePrefix]和[Route],修改index2方法的返回為NotFound()。

技術分享圖片

執行並瀏覽器輸入http://localhost:xxx/api/index/index1和index2,會發現index1有資料,index2找不到網頁。

技術分享圖片

9.一般在前後端分離的專案中,後端返回的事json格式的資料,但是我們瀏覽器中顯示的是xml格式的,這裡需要修改“WebApiConfig”,新增以下程式碼,讓它預設顯示JSON的資料

var formatters = config.Formatters.Where(formatter =>
                  formatter.SupportedMediaTypes.Where(media =>
                  media.MediaType.ToString() == "application/xml" || media.MediaType.ToString() == "text/html").Count() > 0) //找到請求頭資訊中的介質型別
                  .ToList();

            foreach (var match in formatters)
            {
                config.Formatters.Remove(match);  //移除請求頭資訊中的XML格式
            }

開啟瀏覽器請求index1,發現返回的資料已經是json格式的了

技術分享圖片

當然,我們也可以直接指定返回JSON格式的資料,只需要將returen OK(person)改為returen Json(person),效果是一樣的,關於webapi的返回值,可以參考這篇部落格https://www.cnblogs.com/refuge/p/8371415.html

三、引數檢查驗證

在進行請求介面時,需要先對提交的資料引數做一些驗證,驗證資料的合法性,如果不合法就不再通過action,直接返回給客戶端處理。這裡我們使用使用FluentValidation做引數驗證

1.Nuget安裝FluentValidation.WebApi

技術分享圖片

2.修改Pserson類

    [Validator(typeof(PersonValidator))]
    public class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Sex { get; set; }
        public int Age { get; set; }
    }

    public class PersonValidator : AbstractValidator<Person>
    {
        public PersonValidator()
        {
            RuleFor(m => m.Id).NotEmpty().NotNull().WithMessage("Id不能為空");
            RuleFor(m => m.Name).NotEmpty().NotNull().WithMessage("Name不能為空");
        }
    }

3.讓FluentValidation生效,在WebApiConfig中新增如下配置

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        ...
        FluentValidationModelValidatorProvider.Configure(config);
    }
}

4.新建Filter資料夾並新增ParamsFilterAttribute類

public class ParamsFilterAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
             //如果引數非法
            if ( !actionContext.ModelState.IsValid)
            {
                actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest,actionContext.ModelState);
                
            }
            //如果沒有輸入引數
            else if (actionContext.ActionArguments.Values.First() == null)
            {
                actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest,"請輸入引數!");
            }
        }
    }

5.控制器新建一個post請求

        [HttpPost]
        [ParamsFilter]
        [Route("params")]
        public IHttpActionResult Params([FromBody] Person person)
        {
            return Json(person);
        }

postman模擬post請求,在body什麼都不輸入,提示請輸入引數:
技術分享圖片

輸入id,不輸入name,提示name不能為空:

技術分享圖片

輸入正確的引數,返回了資料:

技術分享圖片