Jquery Ajax Post Response Header返回null Always

时间:2014-02-25 05:14:10

标签: jquery ajax http-headers httpresponse

我正在尝试在响应标头“令牌”中读取值。这是我的jquery ajax代码。

 $(document).ready(function () {
        $("#post").click(function () {
                $.ajax({
                type: "Post",
                url: 'http://localhost:1505/api/user/Login',
                data: $("#form1").serialize(),,
                success: function (data, status, xhr) {
                 switch (status) {
                case "Not Found":
                    alert("Wrond Credentials.LogIN Again");
                    break;
                case "success":
                    alert("Hi");
                    var token= xhr.getResponseHeader("Token");
                    alert(token);
                    break;
            }
        }
            });
        });
    });

我检查了我在chrome“Inspect Element”中得到的响应标题,并确认它存在。但是当我在javascript代码中放置一个断点并检查getResponseHeader函数返回的值时,它是一个null。

这是我添加标题的方式

 public string Login(User user)
    {
        if (ModelState.IsValid)
        {
            var found = (from p in db.Users
                         where (p.user == user.user && p.password == user.password)
                         select p).FirstOrDefault();
            if (found == null)
            {
                return "Not Found";
            }
          //  HttpResponseMessage response2 = Request.CreateResponse(HttpStatusCode.Found);
            Token token = new Token();
            string resptok = token.Generate(user);
            HttpContext.Current.Response.AddHeader("Token", resptok);
            return "Found";
        }

我还有一个处理程序类来启用CORS。这是它的代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net.Http;
using System.Threading.Tasks;
using System.Threading;
using System.Net;

namespace AuthenticationDemo.Handlers
{
   public class CorsHandler : DelegatingHandler
{
    const string Origin = "Origin";
    const string AccessControlRequestMethod = "Access-Control-Request-Method";
    const string AccessControlRequestHeaders = "Access-Control-Request-Headers";
    const string AccessControlAllowOrigin = "Access-Control-Allow-Origin";
    const string AccessControlAllowMethods = "Access-Control-Allow-Methods";
    const string AccessControlAllowHeaders = "Access-Control-Allow-Headers";

    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        bool isCorsRequest = request.Headers.Contains(Origin);
        bool isPreflightRequest = request.Method == HttpMethod.Options;
        if (isCorsRequest)
        {
            if (isPreflightRequest)
            {
                return Task.Factory.StartNew<HttpResponseMessage>(() =>
                {
                    HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
                    response.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First());

                    string accessControlRequestMethod = request.Headers.GetValues(AccessControlRequestMethod).FirstOrDefault();
                    if (accessControlRequestMethod != null)
                    {
                        response.Headers.Add(AccessControlAllowMethods, accessControlRequestMethod);
                    }

                    string requestedHeaders = string.Join(", ", request.Headers.GetValues(AccessControlRequestHeaders));
                    if (!string.IsNullOrEmpty(requestedHeaders))
                    {
                        response.Headers.Add(AccessControlAllowHeaders, requestedHeaders);
                    }

                    return response;
                }, cancellationToken);
            }
            else
            {
                return base.SendAsync(request, cancellationToken).ContinueWith<HttpResponseMessage>(t =>
                {
                    HttpResponseMessage resp = t.Result;
                    resp.Headers.Add(AccessControlAllowOrigin, request.Headers.GetValues(Origin).First());
                    return resp;
                });
            }
        }
        else
        {
            return base.SendAsync(request, cancellationToken);
        }
    }
}

}

0 个答案:

没有答案