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 = "", Age = 18 },
              new Person { Id = 1, Name = "王二", Sex = "", Age = 22 },
               new Person { Id = 1, Name = "麻子", Sex = "", 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不能為空:

 輸入正確的參數,返回了數據:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM