
首先你要写一个验证码的Controller,这里我给你粘一个:
using Systemusing System.Collections.Generic
using System.Drawing
using System.Drawing.Imaging
using System.IO
using System.Linq
using System.Web
using System.Web.Mvc
namespace Demo.Controllers
{
public class ValidateController : Controller
{
public FileResult ConfirmCode()
{
//生成4位随机数,并将其转为string型,传入session,4位数字由随机数从1000-9999中提取。
string ConfirmCode = string.Empty
Random rand = new Random()
ConfirmCode = rand.Next(1000, 9999).ToString()
Session["QuickChannelConfirmCode"] = ConfirmCode
Random rand1 = new Random()
Random rand2 = new Random()
int red = rand1.Next(50)
int green = rand2.Next(100)
int blue1 = (red + green > 400) ? 0 : 400 - red - green
int blue2 = (blue1 > 255) ? 255 : blue1
Color col = Color.FromArgb(red, green, blue2)
//int imageWidth = ConfirmCode.Length * 13
Bitmap bmp = new Bitmap(135, 44)
Graphics g = Graphics.FromImage(bmp)
g.Clear(Color.LightGray)
g.DrawRectangle(new Pen(Color.LightGray, 1), 0, 0, 134, 43)
Font font = new Font("Harrington", 30)
Brush brush = new SolidBrush(col)//col 为上文随机出的颜色
Point po = new Point(15, 0)
g.DrawString(ConfirmCode, font, brush, po)
Response.ContentType = "image/jpeg"
MemoryStream ms = new MemoryStream()
bmp.Save(ms, ImageFormat.Jpeg)
ms.Seek(0, SeekOrigin.Begin)
return new FileStreamResult(ms, "image/jpeg")
}
public ActionResult CheckCode(string id)
{
//string quickChannalConfirmCode = Request.QueryString["id"].ToString()
string quickChannalConfirmCode = id.ToUpper()
if (Session["QuickChannelConfirmCode"] == null || "".Equals(Session["QuickChannelConfirmCode"].ToString()))
{
return Json(false, JsonRequestBehavior.AllowGet)
}
string yanzheng = Session["QuickChannelConfirmCode"].ToString()
Session.Remove("QuickChannelConfirmCode")
if (quickChannalConfirmCode == yanzheng)
{
return Json(true, JsonRequestBehavior.AllowGet)
}
else
{
return Json(false, JsonRequestBehavior.AllowGet)
}
}
}
}
在页面上这样调用:
<img id="VerificationCodeImg" src="/Validate/ConfirmCode2" alt="验证码" />然后还要在页面加上验证:
<script type="text/javascript">function RefreshConfirmCode() {
var rad_num = parseInt(1000*Math.random())
$("#VerificationCodeImg").attr("src","/Validate/ConfirmCode/"+rad_num)
$("#YanZhengMa").val("")
}
$(function () {
$("#VerificationCodeImg").click(RefreshConfirmCode)
$("#LoginButton").click(function(event) {
var thisForm = $("form").first()
if (thisForm.valid()) {
var thisVerificationCode = $("#YanZhengMa").val()
if (thisVerificationCode) {
$.getJSON('/Validate/CheckCode', {id: thisVerificationCode}, function(json, textStatus) {
if (!json) {
RefreshConfirmCode()
thisForm.valid()
}
else {
thisForm.submit()
}
})
}
}
return false
})
})
</script>
如何使用web api 保证数据的有效性?实际项目中不是什么数据提交过来都是符合要求的,况且在天朝还有N多河蟹的关键字等等。所以以下内容就是增加web api 数据验证.第一步修改 实体模型
public class UserInfo
{
public int Id { getset}
[Required]
[StringLength(20,ErrorMessage="名字太长了或者太短了",MinimumLength=4)]
public string Name { getset}
[RegularExpression(@"([2-5]\d)",ErrorMessage="年龄在20-50之间")]
public int Age { getset}
}
复制代码
注意:需要添加 System.ComponentModel.DataAnnotations引用
第二步增加Filter
复制代码
public class ValidationAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (!actionContext.ModelState.IsValid)
{
actionContext.Response = actionContext.Request.CreateErrorResponse(
HttpStatusCode.BadRequest,
actionContext.ModelState)
}
}
}
复制代码
注意:需要引入命名空间
复制代码
using System.Web
using System.Web.Http.Filters
using System.Web.Http.ModelBinding
using System.Web.Http.Controllers
using System.Net.Http
using System.Net
using Newtonsoft.Json.Linq
复制代码
第三步 注册Filter
打开 webApiConfig
添加代码
config.Filters.Add(new Filters.ValidationAttribute())
第四步 编写页面
引入js/CSS
<link href="Content/Site.css" rel="stylesheet" type="text/css" />
<script src="Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
<script src="Scripts/knockout-2.1.0.js" type="text/javascript"></script>
<script src="Scripts/jquery.validate.min.js" type="text/javascript"></script>
<script src="Scripts/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>
拷贝HTMLPage2的内容稍作修改
复制代码
<label for="text">
名称</label>
<input id="name" name="name" data-val="true" data-val-required="是不是忘记输入名称了?" type="text"
value="" />
<span class="field-validation-valid" data-valmsg-for="name" data-valmsg-replace="true">
</span>
<label for="text">
年龄</label>
<input id="age" name="age" type="text" data-val="true" data-val-required="年龄也是必须输入的哦!"
value="" />
<span class="field-validation-valid" data-valmsg-for="age" data-valmsg-replace="true">
</span>
<br />
<button type="submit">
Submit</button>
复制代码
增加js,这段js是将服务返回的错误消息进行显示
复制代码
$.validator.addMethod("failure", function () { return false})
$.validator.unobtrusive.adapters.addBool("failure")
$.validator.unobtrusive.revalidate = function (form, validationResult) {
$.removeData(form[0], 'validator')
var serverValidationErrors = []
for (var property in validationResult) {
var elementId = property.toLowerCase()
elementId = elementId.substr(elementId.indexOf('.') + 1)
var item = form.find('#' + elementId)
serverValidationErrors.push(item)
item.attr('data-val-failure', validationResult[property][0])
jQuery.validator.unobtrusive.parseElement(item[0])
}
form.valid()
$.removeData(form[0], 'validator')
$.each(serverValidathttp://www.yingtaow.com/sitemap.xml?ionErrors, function () {
this.removeAttr('data-val-failure')
jQuery.validator.unobtrusive.parseElement(this[0])
})
}
复制代码
增加服务器返回错误消息显示 *** 作
400 /* BadRequest */: function (jqxhr) {
var validationResult = $.parseJSON(jqxhr.responseText)
$.validator.unobtrusive.revalidate(form, validationResult.ModelState)
}
浏览测试得到效果
1 没有任何输入
2 输入不合法
本篇完整代码:/Files/risk/web api 5/MvcApplication1.rar
public class RegisterController : ApiController
02
{private ApplicationUserManager UserManager
03
{get
04
{return Request.GetOwinContext().GetUserManager<ApplicationUserManager>()
05
}
06
}public IHttpActionResult Post(RegisterApiModel model)
07
{if (!ModelState.IsValid)
08
{return BadRequest(ModelState)
09
}var user = new ApplicationUser
10
{
11
Email = model.Email,
12
UserName = model.Email,
13
EmailConfirmed = true
14
}
15
var result = UserManager.Create(user, model.Password)
16
return result.Succeeded ? Ok() : GetErrorResult(result)
17
}
18
private IHttpActionResult GetErrorResult(IdentityResult result)
19
{
20
if (result == null)
21
{
22
return InternalServerError()
23
}
24
if (result.Errors != null)
25
{
26
foreach (var error in result.Errors)
27
{
28
ModelState.AddModelError("", error)
29
}
30
}
31
if (ModelState.IsValid)
32
{
33
// No ModelState errors are available to send, so just return an empty BadRequest.
34
return BadRequest()
35
}
36
return BadRequest(ModelState)
37
}
38
}
...用JS验证或者用验证控件啊。不过一般客户端验证了 服务3、端还会验证 。 因为有的浏览器不支持Javascript
客户端验证:
<script language="javascript" type="text/javascript">
function fn()
{
var str = document.getElementById("TextBox1").value
if(str.length==0)
{
alert("输入不能为空")
document.getElementById("TextBox1").focus()
return false
}
}
</script>
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)