Asp.net mvc 如何在ASP.NET MVC中向请求添加标题

Asp.net mvc 如何在ASP.NET MVC中向请求添加标题,asp.net-mvc,request-headers,Asp.net Mvc,Request Headers,在发送获取操作的请求之前,是否可以添加一些标题? 我要做的是指定如下标题: -Accept application/json -Content-Type application/json 。。。 在我的控制器中输入GET方法之前。如果使用发送带有Accept和Content-Type头的GET请求,则如下所示: HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUri)

在发送获取操作的请求之前,是否可以添加一些标题? 我要做的是指定如下标题:

-Accept application/json

-Content-Type application/json
。。。 在我的控制器中输入GET方法之前。

如果使用发送带有Accept和Content-Type头的GET请求,则如下所示:

        HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUri)
        {
            Content = content,
        };
        request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");

        HttpResponseMessage response = await client.SendAsync(request);
$.ajax({
  url: 'URL HERE',
  type: 'GET',
  contentType: "application/json; charset=utf-8",
  dataType: 'json',
  success: function (data) {
    // here goes the data that came from the response..
  }
});
请记住,代码使用的是发送请求的异步版本,因此您必须使用Async关键字来修饰您的方法,以使其正常工作

如果希望从前端发送请求,则应使用ajax,代码如下所示:

        HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, requestUri)
        {
            Content = content,
        };
        request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");

        HttpResponseMessage response = await client.SendAsync(request);
$.ajax({
  url: 'URL HERE',
  type: 'GET',
  contentType: "application/json; charset=utf-8",
  dataType: 'json',
  success: function (data) {
    // here goes the data that came from the response..
  }
});
这个怎么样

$.ajax({
    url: '@Url.Action("GetData", "Home")',
    type: "GET",
    contentType: "application/json; charset=utf-8",
    dataType: 'json',
    success: function (result) {
    }
});
控制器

您可以使用以下标题:


您使用什么发送请求HttpClient、WebClient?请提供一些代码。