创建Web API并使用

昨晚有教一个网友在ASP.NET MVC里,创建Web API和在MVC视图中应用此API。

可以在ASP.NET MVC中,创建程序的model:

namespace Insus.NET.Models
{
    public class Weather
    {
        private int _Month;

        public int Month
        {
            get { return _Month; }
            set { _Month = value; }
        }


        private string _Season;

        public string Season
        {
            get
            {
                return _Season;
            }
            set { _Season = value; }
        }       
    }
}
Source Code


model创建好了,可以开始创Web API:


如果你的环境是第一次创建Web API的,它会打开一个文本,是教诉你怎样配置Global.asax.cs的:

 
稍后注意一下,api的路由注册应该放在mvc的路由前面。

 

接下来,为你的api接口写方法或是函数:


namespace Insus.NET.Apis
{
    public class WeatherAPIController : ApiController
    {
        [Route("api/WeatherAPI/ApiMethod")]
        [HttpPost]
        public Weather ApiMethod(Weather w)
        {   
            var a = new List<int>() { 1, 2, 3 };
            if (a.Contains(w.Month))
                w.Season = "春季";

            var b = new int[] { 4, 5, 6 };
            if (b.Contains(w.Month))
                w.Season = "夏季";

            IEnumerable<int> c = new List<int>() { 7, 8, 9 };
            if (c.Contains(w.Month))
                w.Season = "秋季";

            var d = "10,11,12".Split(new char[] { ',' }).Select(i => Int32.Parse(i)).ToArray();
            if (d.Contains(w.Month))
                w.Season = "冬季";

            return w;
        }
    }
}
Source Code


以上内容全是Web API的建设。前端介面,就可以使用它们了。
 
现在ASP.NET MVC网站上,添加一个视图,并添加一些html:



为铵钮补充click事件,那是使用jQuery的ajax来POST用户输入的月份,然后系统返回季度:

 $(function () {
            $("#btnConvert").click(function () {
                var obj = {};
                obj.Month = $("#txtMonth").val();
               
                $.ajax({
                    type: "POST",
                    url: "/api/WeatherAPI/ApiMethod",
                    data: JSON.stringify(obj),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (response) {
                        $('.label').html("你输入的月份:" + response.Month + ";  转换季度是:" + response.Season + "。");
                    },
                    failure: function (response) {
                        alert(response.responseText);
                    },
                    error: function (response) {
                        alert(response.responseText);
                    }
                });
            });
        });
Source Code


演示:


 

原文地址:https://www.cnblogs.com/insus/p/7771428.html