【问题标题】:How can I add headers to my request in ASP.NET MVC如何在 ASP.NET MVC 中向我的请求添加标头
【发布时间】:2016-12-06 05:47:52
【问题描述】:

是否可以在向GET action 发送请求之前添加一些标头? 我想要做的是指定像这样的标题:

-Accept application/json

-Content-Type application/json

... 在我的控制器中输入GET 方法之前。

【问题讨论】:

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

标签: asp.net-mvc request-headers


【解决方案1】:

您可以使用这些:headers:

$.ajax({
            url: '/api/Apicontrolle/GetAccion',
            //url: '/MvcController/GetAccion',
            method: 'GET',
            data: {DATA},
            traditional: true,
            async: true,
            dataType: 'JSON',
            headers: {'Authorization':'Bearer '+ sessionStorage.getItem("accessToken")},
            success: function (response){},......

【讨论】:

    【解决方案2】:

    如果您使用 HttpClient 发送带有 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);
    

    请记住,代码使用异步版本发送请求,因此您必须使用“Async”关键字装饰您的方法才能使其工作。

    如果你想从前端发送请求,你应该使用 ajax,你的代码看起来像这样:

    $.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..
      }
    });
    

    【讨论】:

      【解决方案3】:

      这个怎么样?

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

      控制器

      public ActionResult GetData()  
      {
         return Json("What I want to send", JsonRequestBehavior.AllowGet);
      }
      

      【讨论】:

        猜你喜欢
        • 2021-02-10
        • 1970-01-01
        • 1970-01-01
        • 2017-06-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多