使用[ValidateAntiForgeryToken]的angularjs $ http.post到MVC控制器

时间:2015-05-19 14:07:58

标签: asp.net-core asp.net-core-mvc angularjs-http

使用[ValidateAntiForgeryToken]从angular到MVC控制器的$ http.post方法会抛出500内部服务器错误,并显示以下消息。 [我们正在调用控制器在标头和数据中传递__RequestVerificationToken。] 我们正在使用Microsoft.AspNet.Mvc-6.0.0-beta4

<span class="light exception">System.InvalidOperationException</span><br />
<span class="heavy">Incorrect Content-Type: application/json;charset=UTF-8</span><br />
<div class="stacktrace">
<pre><span class="faded">at Microsoft.AspNet.Http.Core.</span>FormFeature.&lt;ReadFormAsync&gt;d__12.MoveNext<span class="faded">
;()</span></pre>
    <br /><pre><span class="faded">at System.Runtime.CompilerServices.</span>TaskAwaiter.ThrowForNonSuccess<span class="faded">(Task task)</span></pre>
    <br /><pre><span class="faded">at System.Runtime.CompilerServices.</span>TaskAwaiter.HandleNonSuccessAndDebuggerNotification<span class="faded">(Task task)</span></pre>
    <br /><pre><span class="faded">at System.Runtime.CompilerServices.</span>TaskAwaiter&lt;TResult&gt;.GetResult<span class="faded">()</span></pre>
    <br /><pre><span class="faded">at Microsoft.AspNet.Mvc.</span>AntiForgeryTokenStore.&lt;GetFormTokenAsync&gt;d__4.MoveNext<span class="faded">()</span></pre>

1 个答案:

答案 0 :(得分:0)

我为此编写了一个自定义验证属性(适用于beta4)。 像常规一样使用它。

public class ValidateAntiForgeryTokenFromHeaderAttribute : ActionFilterAttribute, IFilter {
    public override void OnActionExecuting (ActionExecutingContext actionContext) {
        if (actionContext == null) throw new ArgumentNullException(nameof(actionContext));

        base.OnActionExecuting(actionContext);

        AntiForgery antiForgery = actionContext.HttpContext.ApplicationServices.GetService(typeof(AntiForgery)) as AntiForgery;

        var options = actionContext.HttpContext.ApplicationServices.GetService(typeof(IOptions<MvcOptions>)) as IOptions<MvcOptions>;
        var config = options.Options.AntiForgeryOptions;

        var request = actionContext.HttpContext.Request;

        String cookieToken = request.Cookies[config.CookieName];
        String formToken   = request.Headers.Get("X-XSRF-Token");

        antiForgery.Validate(actionContext.HttpContext, cookieToken, formToken);
    }
}

在角度方面,我在应用的$http方法中设置run,如下所示:

$http.defaults
     .headers
     .common[$http.defaults.xsrfHeaderName] = angular.element("input[name='__RequestVerificationToken']")
                                                     .attr("value");