Kategori: Asp.Net MVC

HandleErrorAttribute Customize Request Ajax

 

public override void OnException(ExceptionContext filterContext)
{
	var controllerName = filterContext.RouteData.Values["controller"];
	var actionName = filterContext.RouteData.Values["action"];
	var userName = HttpContext.Current.User.Identity.Name;
	var area = filterContext.RouteData.DataTokens["area"];

	if (filterContext.HttpContext.Request.IsAjaxRequest())
	{
		filterContext.ExceptionHandled = true;

		filterContext.HttpContext.Response.Clear();
		filterContext.HttpContext.Response.StatusCode = Convert.ToInt32(System.Net.HttpStatusCode.InternalServerError);
		filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
		filterContext.Result = new JsonResult
		{
			Data = new { result = false, ExceptionMessage = filterContext.Exception.Message },
			JsonRequestBehavior = JsonRequestBehavior.AllowGet
		};
	}

	base.OnException(filterContext);
}

 

Asp.net MVC Razor Html Helper ile Captcha

Basit kullanımlı, basit bir captcha ihtiyacımı karşılamak için geliştirdiğim kod blokları aşağıda ki gibidir.

Razor olarak kullanmak için Html Extensions

    public static partial class HtmlExtensions
    {
        public static MvcHtmlString Captcha(this HtmlHelper helper)
        {
            string result = string.Empty;

            var panel = new TagBuilder("div");
            panel.Attributes.Add("class", "panel panel-default");

            var mainDiv = new TagBuilder("div");
            mainDiv.Attributes.Add("id", "captchaHtmlExtensions");
            mainDiv.Attributes.Add("ct-captcha", "");

            var imageDiv = new TagBuilder("div");
            imageDiv.Attributes.Add("id", "captchaImage");
            imageDiv.Attributes.Add("class", "col-md-12");
            imageDiv.Attributes.Add("onclick", "getCaptchaImage()");

            var input = new TagBuilder("input");
            input.Attributes.Add("name", "captchaValue");
            input.Attributes.Add("id", "captchaValue");
            input.Attributes.Add("class", "form-control");
            input.Attributes.Add("type", "form-text");
            input.Attributes.Add("placeholder", "Kodu Giriniz");

            var text = new TagBuilder("h6");
            text.InnerHtml = "Doğrulama Kodu";
            text.Attributes.Add("class", "panel-heading panel-title");

            panel.InnerHtml += text.ToString();
            panel.InnerHtml += mainDiv.ToString();
            panel.InnerHtml += imageDiv.ToString();
            panel.InnerHtml += input.ToString();

            result += panel.ToString(TagRenderMode.Normal);

            return MvcHtmlString.Create(result);
        }
    }

base64 olarak geri dönen captcha image methodu:

        public static string GetCaptchaImageByBase64()
        {
            bool noisy = true;
            var random = new Random((int)DateTime.Now.Ticks);

            int imageWidth = 100;
            int imageHeight = 30;

            //generate text
            int length = 3;
            string characters = "ABCDEFGHIJKLMNOPRSTUVYZ";
            StringBuilder result = new StringBuilder(length);
            for (int i = 0; i < length; i++)
            {
                result.Append(characters[random.Next(characters.Length)]);
            }

            //generate text

            var captcha = result.ToString();

            //result
            HttpContext.Current.Session["CaptchaImageResult"] = result.ToString();

            //captchaImage

            using (var mem = new MemoryStream())
            using (var bmp = new Bitmap(imageWidth, imageHeight))
            using (var gfx = Graphics.FromImage((Image)bmp))
            {
                gfx.TextRenderingHint = TextRenderingHint.ClearTypeGridFit;
                gfx.SmoothingMode = SmoothingMode.AntiAlias;
                gfx.FillRectangle(Brushes.White, new Rectangle(0, 0, bmp.Width, bmp.Height));

                if (noisy)
                {
                    int i, r, x, y;
                    var pen = new Pen(Color.Yellow);
                    for (i = 1; i < 8; i++)
                    {
                        pen.Color = Color.FromArgb(
                        (random.Next(0, 255)),
                        (random.Next(0, 255)),
                        (random.Next(0, 255)));

                        r = random.Next(0, (imageWidth / 3));
                        x = random.Next(0, imageWidth);
                        y = random.Next(0, imageHeight);

                        gfx.DrawEllipse(pen, x - r, y - r, r, r);
                    }
                }

                //image add text
                gfx.DrawString(captcha, new Font("Tahoma", 18), Brushes.Gray, 15, 3);

                //generate image stream
                bmp.Save(mem, System.Drawing.Imaging.ImageFormat.Png);
                string srcValue = string.Format("data:image/png;base64, {0}", Convert.ToBase64String(mem.ToArray()));

                return srcValue;
            }
        }

Oluşan captcha image’nı json olarak döndüren method:

        public ActionResult GetCaptchaImageJson()
        {
            return Json(Operations.GetCaptchaImageByBase64(), JsonRequestBehavior.AllowGet);
        }

Javascript function:

$(document).ready(function () {
    $("div").each(function () {

        if ($(this).attr("ct-Captcha") != undefined) {
            getCaptchaImage();

            $("#captchaValue").bind('keyup', function (e) {
                if (e.which >= 97 && e.which <= 122) {
                    var newKey = e.which - 32;
                    e.keyCode = newKey;
                    e.charCode = newKey;
                }
                $("#captchaValue").val(($("#captchaValue").val()).toUpperCase());
            });
        }
    });
});
function getCaptchaImage() {
    $.ajax({
        cache: false,
        async: true, //!!!
        type: "POST",
        url: pureRoot + "Json/GetCaptchaImageJson",
        success: function (data) {
            //console.log(data, "UTIL -> getCaptchaImage -> success");
            $('#captchaImage').html('<div style="margin:5px;"><img src="' + data + '" class="img-responsive" title="Yenilemek için tıklayınız"/></div>')
            $("#captchaValue").val('');
        },
        error: function (xhr, ajaxOptions, thrownError) {
            console.log("Bağlantı sırasında hata oluştu!", "UTIL -> getCaptchaImage -> error");
        }
    });
}

Kullanımı:

@Html.Captcha()

Captcha

Asp.Net MVC 4 Empty Proje Sorunu

* Razor’u tanımama durumu sorunu:

System.Core ve Microsoft.CSharp referance dll versiyonları uyuşmadığından dolayı oluşan hatadır. Çözümü web.config dosyasına

<system.web>
<compilation debug="true" targetFramework="4.5">
  <assemblies>
	<add assembly="System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
	<add assembly="Microsoft.CSharp, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
  </assemblies>
</compilation>
</system.web>

 

* An exception of type ‘System.IO.FileLoadException’ occurred in System.Web.Optimization.dll but was not handled in user code sorunu system.Web.Optimization dll’in gerekli gördüğü WebGrease dll ile versiyon uyuşmaması sorunudur. Belirtilen dll nuget consolende yüklenmelidir.

Install-Package WebGrease -Version 1.5.2