ASP.NET Core offers attributes such as [HttpGet] and [HttpPost] that allow you to restrict the HTTP verbs used to invoke an action. You can also use HttpRequest object's Method property to detect the HTTP verb behind the current request. However, at times you need to know whether a request is an Ajax request or not. You may also need to restrict an action only to Ajax calls. Although thee is no inbuilt way to accomplish this task, you can easily implement such a feature in your application. This article discusses how.

Detecting HTTP method and Ajax request

In order to know the HTTP method being used by the current request you can use the following line of code :

string method = HttpContext.Request.Method;

The HttpRequest object's Method property returns HTTP verb being used by the current request such as GET and POST.

Detecting whether a request is an Ajax request or not requires a bit of different code. The Method property will return the HTTP method whether a request is an Ajax request or otherwise. So, you need to check a special HTTP header. The following line of code shows that :

string requestedWith =
HttpContext.Request.Headers["X-Requested-With"];

The X-Requested-With header returns a string that indicates whether it's an Ajax request or not. An Ajax request will have this header set to XMLHttpRequest. This header value won't be present for normal GET and POST requests (non-Ajax requests).

Ok. So, how do we ensure that our action code gets invoked only if it's an Ajax request. Let's write a fragment of code :

public IActionResult Index()
{
string method = HttpContext.Request.Method; string requestedWith =
HttpContext.Request.Headers["X-Requested-With"]; if (method=="POST")
{
if(requestedWith == "XMLHttpRequest")
{
// code goes here
}
}
return View();
}

Suppose we want to ensure that our action code gets executed only when it's an Ajax POST request. The above piece of code does just that.

Extension method that detects an Ajax request

Although the above piece of code works as expected, it lacks reusability. Let's make it easy to use by wrapping it in an extension method to HttpRequest object.

public static class HttpRequestExtensionMethods
{ public static bool IsAjax(this
HttpRequest request, string httpVerb = "")
{
if (request == null)
{
throw new ArgumentNullException
("Request object is Null.");
} if (!string.IsNullOrEmpty(httpVerb))
{
if (request.Method != httpVerb)
{
return false;
}
} if (request.Headers != null)
{
return request.Headers["X-Requested-With"]
== "XMLHttpRequest";
} return false;
}
}

The above code defines an extension method called IsAjax() on the HttpRequest object. The IsAjax() method also takes httpVerb parameter that can be used to specify an HTTP verb such as GET or POST.

The second if condition checks whether current request's HTTP method matches with what has been provided in the IsAjax() method's httpVerb parameter. If it doesn't a value of false is returned to the caller.

The third if condition checks whether the request is an Ajax request or not. It does so using the X-Requested-With header. If X-Requested-With header value is not XMLHttpRequest we return false.

Once this extension method is added you can see it in the controller like this :

And you can use it like this :

bool isAjax = HttpContext.Request.IsAjax("POST");

The above call to IsAjax() returns true only if the request under consideration is an Ajax POST request.

Creating custom [Ajax] attribute

So far so good. Let's improvise our code further. We will now wrap the Ajax checking logic in a custom attribute named [Ajax] so that you can use it like this :

As you can see the GetEmployee() action is decorated with [Ajax] attribute. And the HttpVerb property of [Ajax] is set to GET.

The [Ajax] attribute ensures that GetEmployee() is invoked only if the request is an Ajax GET request.

Let's dissect the code that makes the [Ajax] attribute:

public class AjaxAttribute : ActionMethodSelectorAttribute
{
public string HttpVerb { get; set; } public override bool IsValidForRequest
(RouteContext routeContext, ActionDescriptor action)
{
return routeContext.HttpContext.
Request.IsAjax(HttpVerb);
}
}

Here, we create AjaxAttribute class, a custom ActionMethodSelectorAttribute. This attribute does the conditional checking of whether a request is an Ajax request or not.

The [Ajax] has HttpVerb property and it also overrides the IsValidForRequest() method. Inside we simply call IsAjax() extension method we created earlier. You can also put the entire request checking logic inside the IsValidForRequest() method.

Testing our code

In order to test our code let's make an Ajax GET and POST request to the GetEmplooyee() action. Notice that the GetEmployee() returns a JSON with certain EmoployeeID, FirstName, and LastName.

<h1>Welcome!</h1>

<button type="button" id="button1">Make Ajax Call</button>

<form method="post" action="/home/GetEmployee">
<button type="submit" id="button2">Submit Form</button>
</form>

The above markup is from Index.cshtml. It shows two <button> elements - one making Ajax request and the other making normal non-Ajax POST request.

A dash of jQuery code is used to make a GET request to the GetEmployees() :

$(document).ready(function () {
$("#button").click(function () {
$.get("/home/GetEmployee", function (data) {
alert(data.employeeID + " " +
data.firstName + " " +
data.lastName);
});
});
});

I won't go into the details of this jQuery code since it is quite straightforward. If suffices to say that the code code attempts to calls the GetEmployee() action using GET method.

The following figure shows a sample run of the page.

What if we make a non-Ajax POST request? See the following run :

As you can see, this time the server returns HTTP status code 404. That's because the request is not an Ajax request. Moreover it's a POST request. So, the [Ajax[ is going to treat it as an invalid request and won't allow the GetEmployees() to execute.

That's it for now! Keep coding !!

Allow Only Ajax Requests For An Action In ASP.NET Core的更多相关文章

  1. Ajax跨域问题及解决方案 asp.net core 系列之允许跨越访问(Enable Cross-Origin Requests:CORS) c#中的Cache缓存技术 C#中的Cookie C#串口扫描枪的简单实现 c#Socket服务器与客户端的开发(2)

    Ajax跨域问题及解决方案   目录 复现Ajax跨域问题 Ajax跨域介绍 Ajax跨域解决方案 一. 在服务端添加响应头Access-Control-Allow-Origin 二. 使用JSONP ...

  2. [React] Create a queue of Ajax requests with redux-observable and group the results.

    With redux-observable, we have the power of RxJS at our disposal - this means tasks that would other ...

  3. MVC中使用Ajax提交数据 Jquery Ajax方法传值到action

    Jquery Ajax方法传值到action <script type="text/javascript"> $(document).ready(function(){ ...

  4. 再谈Jquery Ajax方法传递到action 【转载】

    原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 .作者信息和本声明.否则将追究法律责任.http://cnn237111.blog.51cto.com/2359144/984466 之 ...

  5. 再谈Jquery Ajax方法传递到action(转)

    之前写过一篇文章Jquery Ajax方法传值到action,本文是对该文的补充. 假设 controller中的方法是如下: public ActionResult ReadPerson(Perso ...

  6. 转 Using $.ajaxPrefilter() To Configure AJAX Requests In jQuery 1.5

    Using $.ajaxPrefilter() To Configure AJAX Requests In jQuery 1.5 Posted February 18, 2011 at 6:29 PM ...

  7. Ajax跨域请求action方法,无法传递及接收cookie信息(应用于系统登录认证及退出)解决方案

    最近的项目中涉及到了应用ajax请求后台系统登录,身份认证失败,经过不断的调试终于找到解决方案. 应用场景: 项目测试环境:前端应用HTML,js,jQuery ajax请求,部署在Apache服务器 ...

  8. ASP.NET Core 1.0中实现文件上传的两种方式(提交表单和采用AJAX)

    Bipin Joshi (http://www.binaryintellect.net/articles/f1cee257-378a-42c1-9f2f-075a3aed1d98.aspx) Uplo ...

  9. Upload Files In ASP.NET Core 1.0 (Form POST And JQuery Ajax)

    Uploading files is a common requirement in web applications. In ASP.NET Core 1.0 uploading files and ...

随机推荐

  1. SQL优化 MySQL版 - 多表优化及细节详讲

    多表优化及细节详讲 作者 : Stanley 罗昊 [转载请注明出处和署名,谢谢!] 注:本文章需要MySQL数据库优化基础或观看前几篇文章,传送门: B树索引详讲(初识SQL优化,认识索引):htt ...

  2. springcloud情操陶冶-bootstrapContext(三)

    本文则将重点阐述context板块的自动配置类,观察其相关的特性并作相应的总结 自动配置类 直接查看cloudcontext板块下的spring.factories对应的EnableAutoConfi ...

  3. Windows环境下安装配置Mosquitto服务及入门操作介绍

    关键字:在windows安装mosquitto,在mosquitto中配置日志,在mosquitto中配置用户账号密码 关于Mosquitto配置的资料网上还是有几篇的,但是看来看去,基本上都是基于L ...

  4. 简述ADO.NET的连接层

    前面曾提到过ADO.NET的连接层允许通过数据提供程序的连接.命令.数据读取器对象与数据库进行交互.当想连接数据库并且使用一个数据读取器对象来读取数据时.需要实现下面的几个步骤 * 创建.配置.打开连 ...

  5. while,for,if输入账号密码判断(还请各位大牛能够优化,本人刚学习一周)

    AccountNumber1 = [] password1 = [] flag = True while flag: num = 0 a = 1 print('-----------这是个欢迎界面-- ...

  6. 一看就能学会的H5视频推流方案

    本文由云+社区发表 作者:周超 导语 随着直播平台爆发式增长,直播平台从 PC 端转战移动端,紧跟着直播的潮流,自己学习实现了一套简单的 H5 视频推流的解决方案,下面就给小伙伴们分享一下自己学习过程 ...

  7. 工具资源系列之给mac装个虚拟机

    mac 系统安装虚拟机目前有两种主流软件,一种是 Parallels Desktop ,另一种是 vmware. 本教程选用的是 vmware ,因为我之前 windows 上安装的虚拟机软件就是vm ...

  8. IOS跟ANDROID的区别

    大家总是会纠结哪个手机系统会更加适合自己,那就由小编我简要介绍一下IOS和安卓的区别吧! 运行机制:安卓是虚拟机运行机制,IOS是沙盒运行机制.这里再说明一下这两者的主要不同之处.安卓系统中应用程序的 ...

  9. base64图片存储

    将图片转换为Base64编码,可以让你很方便地在没有上传文件的条件下将图片插入其它的网页.编辑器中. 这对于一些小的图片是极为方便的,因为你不需要再去寻找一个保存图片的地方. Base64编码在ora ...

  10. 这20个常规Python语法你都搞明白了吗?

    Python简单易学,但又博大精深.许多人号称精通Python,却不会写Pythonic的代码,对很多常用包的使用也并不熟悉.学海无涯,我们先来了解一些Python中最基本的内容. Python的特点 ...