C# 为什么可以';我不能在Web Api中获取标题吗?
我找了很多,都找不出我遗漏了什么 我尝试在ajax调用中发送标题:C# 为什么可以';我不能在Web Api中获取标题吗?,c#,asp.net-web-api,jsonp,C#,Asp.net Web Api,Jsonp,我找了很多,都找不出我遗漏了什么 我尝试在ajax调用中发送标题: $.ajax({ type: "GET", url: url, dataType: 'jsonp', headers: { "Authorization": "98765", "X-My-Secret-Token": "WhyCantIGetThis", "JustAnotherTest": "314987" },
$.ajax({
type: "GET",
url: url,
dataType: 'jsonp',
headers: { "Authorization": "98765", "X-My-Secret-Token": "WhyCantIGetThis", "JustAnotherTest": "314987" },
//beforeSend: function (request) {
// request.setRequestHeader("Authorization", "98765"); -> I tried this way too
//},
success: function (data) {
$('#value1').html(data);
}
})
把它放进去:
public override void OnActionExecuting(HttpActionContext actionContext)
{
var header_X_My_Secret_Token = actionContext.Request.Headers.SingleOrDefault(x => x.Key == "X-My-Secret-Token");
var header_Authorization = actionContext.Request.Headers.SingleOrDefault(x => x.Key == "Authorization");
var header_JustAnotherTest = actionContext.Request.Headers.SingleOrDefault(x => x.Key == "JustAnotherTest");
var heeder_Authorization2 = actionContext.Request.Headers.Authorization;
}
但都是空的。有人能告诉我为什么吗?谢谢
[编辑]
我可以在同一个域ajax调用中获取标题。但我也需要在跨域中获得它。你怎么知道的?感谢您在跨域请求中向发送头之前,chrome将使用CORS确定可以发送哪些头。要使浏览器能够发送所需的标题,可以向控制器添加选项方法
public HttpResponseMessage Options()
{
var response = new HttpResponseMessage();
response.Headers.Add("Access-Control-Allow-Headers", Request.Headers.GetValues("Access-Control-Request-Headers").FirstOrDefault() );
response.Headers.Add("Access-Control-Allow-Origin", "*");
response.Headers.Add("Access-Control-Allow-Method", "GET");
return response;
}
你可以试试这个,在我的情况下,它是有效的
IEnumerable<string> values = new List<string>();
actionContext.Request.Headers.TryGetValues("Authorization", out values);
IEnumerable values=new List();
actionContext.Request.Headers.TryGetValues(“授权”,输出值);
对于仍在搜索答案的任何人
我只需要启用CORS:
安装软件包Microsoft.AspNet.WebApi.Cors
使用System.Web.Http;
命名空间Web服务
{
公共静态类WebApiConfig
{
公共静态无效寄存器(HttpConfiguration配置)
{
EnableCors();\\n我遇到同样的问题,您解决了吗?
using System.Web.Http;
namespace WebService
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
EnableCors(); \\<==============
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}