RedApple
RedApple

Reputation: 201

How can I read the current headers without making a new request with C#?

Since JS cannot get the initial page request, can C# get the current headers without making a new request?

The main goal is to be able to determine who is accessing the page by looking at the HTTP header that has a custom value "uid": "world" that is passed in. After determining it, the value is then displayed on that same page.

Hello "world"

Can this be done in C#? How?

Upvotes: 2

Views: 11922

Answers (3)

Troy Carlson
Troy Carlson

Reputation: 3111

To access the headers within your MVC controller, you can use this:

Controller

public ActionResult Index()
{
    var uid = System.Web.HttpContext.Current.Request.Headers["uid"];

    // Add your view model logic here...
    var model = new TestModel
    {
        HeaderValue = uid
    };

    return View(model);
}

View

@model MyProject.Models.TestModel

<div>
    Hello @Model.HeaderValue
</div>

Upvotes: 4

Suncat2000
Suncat2000

Reputation: 1086

In your controller, use System.Mvc.Web.Mvc.Request.Headers to get the headers from the current request.

If you are using Razor, you can include @Request.Headers directly on your .cshtml page and share the contents with Javascript, if you want.

Upvotes: 0

mason
mason

Reputation: 32693

In ASP.NET, you can read the Headers from the Request object. My answer is assuming Web Forms, please update your question if you're not using Web Forms (it's important to include that information in your initial question in the future).

<asp:Label runat="server" id="HeaderLbl" />

And code behind:

using System.Web; //add this to the top of your class if it's not already there

protected void Page_Load(object sender, EventArgs e)
    {
    HeaderLbl.Text = Request.Headers["uid"];
    }

Upvotes: 2

Related Questions