创建Web API并使用
2024-10-12 20:15:10
昨晚有教一个网友在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>() { , , };
if (a.Contains(w.Month))
w.Season = "春季"; var b = new int[] { , , };
if (b.Contains(w.Month))
w.Season = "夏季"; IEnumerable<int> c = new List<int>() { , , };
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
演示:
最新文章
- Thread多线程(二):Runnable
- JS 继承总结
- splice slice
- struts json登录
- poj1375Intervals(点到圆的切线)
- bug_ _java.lang.IllegalArgumentException: View not attached to window manager
- C# IO操作(四)大文件拷贝(文件流的使用)、文件编码
- 前端面试题之js篇
- 更改yum网易 阿里云的yum源。
- [WARNING] Warning: selected war files include a WEB-INF/web.xml which will be ignored (webxml attribute is missing from war task, or ignoreWebxml attribute is specified as &#39;true&#39;)
- POJ 3347 Kadj Squares (线段覆盖)
- C#之实参和形参
- maven编译时错误:无效的目标发行版
- ASP.NET Core的身份认证框架IdentityServer4--(2)API跟WEB端配置
- 匿名函数,结合闭包的写法,js对象的案例
- django-个人博客登录及权限验证功能的实现
- 什么是云?Iaas,Paas和SaaS
- A implementaion for 2D blue noise
- sql分页存储过程比较
- xdoj-1149(多重集合+容斥原理+组合数取模)
热门文章
- 关于z-index使用方法
- SVM中径向基函数与高斯核的区别 Difference between RBF and Gaussian kernel in SVM
- Android学习笔记----Java字符串MD5加密
- Linux高可靠技术
- loadrunner&#160;运行脚本-Run-time&#160;Settings-Browser&#160;Enmulation设置详解
- (网页)angular js 终极购物车(转)
- json替换jsonp实现跨域请求
- Python数据清洗基本流程
- Instruments模板介绍(更新中...)
- java基础面试题(Servlet生命周期)