ASP.NET MVC 5 not sending X-Frame-Options header by default - c#

This article seems to suggest that an ASP.NET MVC 5 website automatically sends the X-Frame-Options HTTP header with the value SAMEORIGIN.
I would like that by default, I am observing that for my website, it doesn't.
Even adding the following line of code, which would have been unnecessary if the default behavior would have been to send the header, does not seem to send it.
AntiForgeryConfig.SuppressXFrameOptionsHeader = false;
I can add an action filter attribute and do that explicitly. But I was wondering if I were missing something if I wanted to have that header be sent by default with the SAMEORIGIN value?
I am using ASP.NET MVC 5.2.4 targeting .NET Framework 4.6.1.

It will it add by default if you will use #Html.AntiForgeryToken() on a view.
If you don't use it, you need to add this header explicitly e.g. in the action filter attribute.

Related

Modify route of incoming request in Web API using ASP Net Core

I am working on a Web API project using Asp Net Core 2.1.
My existing Web API has the following Get method (and numerous other methods like these):
[HttpGet("GetEmployeByName/{Name}")]
public Employee GetEmployeeByName(string name)
{... some code...}
This responds to the following incoming request:
http://localhost:8080/Employee/GetEmployeeByName/{Name}
Now my requirement is such that some of the APIs could be called by passing an additional id such as:
http://localhost:8080/Employee/{Id}/GetEmployeeByName/{Name}.
I still need to map it to the original method without changing the route.
This can be done using ASP Net Core's feature of URL Rewrite and the URL can be re-written without the id.
However what i want to do is to capture the {Id} as well and save it to Session\ Context.
Does anyone know how to extract the id and rewrite the URL.
Maybe you can find what you need here optional parameters web api, you would need to add that parameter at the end as optional parameters always go at the end, also you could try to use both versions of the end point encapsulate the logic and reuse it on both versions.

.net-core WebApp Dynamic Route to Controller

I'm trying to migrate an existing asp.net website to dotnet-core (version: 1.0.3), and have some trouble with the routing of the requests.
The old Structure was: web.site.com/[categorie]/{id?}
Now with the new envoirment it should be the same, but i cant get it work.
Since the [categorie] field comes out of the Database, and the position in dotnet-core is usualy the controller.
If this would be static i could proberly just define x Routes, but this can be changed on the fly.
So i need a hint or maybe a Solution how to route a dynamic set of [categorie] to the same Controller.
Cheers Isparia

ASP.NET MVC OutputCache does not store Custom Headers

My application uses ASP.NET MVC 5 with OutputCache (in detail, we use MVCDonutCaching) to cache high traffic sites and expensive routes.
Some of the Actions have a Custom ActionFilter which adds a Content-Range header depending on the view model. Without caching it works like charm. When the cache is enabled the first hit is ok (Content-Range header is present in the response) - but the second one only contains Content-Type and the HTML/JSON Response and our custom Content-Range header is missing (which breaks the client functionality).
Is there any way to enable proper header caching without writing an own OutputCache implementation?
Thank you very much.
The cached response is a "304 - Not Modified" HTTP Response, and that kind of response is not expected to return entity headers (except some exceptions like "Last-Modified").
The "Content-Range" header you are trying to return is an entity header:
http://www.freesoft.org/CIE/RFC/2068/178.htm
Here is a full list of Entity headers:
https://www.rfc-editor.org/rfc/rfc2616#section-7.1
The reason why 304 is not returning entity headers is that the 304 response is not supposed to return a full representation of the target resource, since nothing changed.
The 304 (Not Modified) status code indicates that a conditional GET
or HEAD request has been received and would have resulted in a 200
(OK) response if it were not for the fact that the condition has
evaluated to false. In other words, there is no need for the server
to transfer a representation of the target resource because the
request indicates that the client, which made the request
conditional, already has a valid representation;
That means that entity headers should not be transferred again. This ensures consistency, and also has some performance benefits.
If the conditional GET used a strong cache validator (see section 13.3.3), the response SHOULD NOT include other entity-headers. Otherwise (i.e., the conditional GET used a weak validator), the response MUST NOT include other entity-headers; this prevents inconsistencies between cached entity-bodies and updated headers.
https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-p4-conditional-23#section-4.1
My conclusion is that ASP.NET and IIS are interpreting this specification correctly, and what you are trying to do is NOT supported. A prove for that is that Apache, and other popular web servers do the same as explained above.
If you still need that header in your 304 you will have to identify and replace (if possible) the components responsible for filtering the 304 responses.

WebAPI Cookies with ReportViewerWebControl

I have an MVC application that also includes an ASP.Net WebForm to host the MS ReportViewer Web Control. We make extensive use of WebAPI to allow for client posting from Knockout viewmodels client side.
In this application, we're making use of cookies to maintain a few minor pieces of user data--a GUID, an int, and a bool.
What we see at present is that the application works correctly until a user opens the ReportViewer. At that point, we're no longer able to read any cookies from the request headers. This has been consistently reproduced in several browsers.
Examination with Fiddler has revealed that the cookies are properly posted to the server. In the first case, the cookie value is as follows:
theCulture=en-US; ASP.NET_SessionId=uhmquapd1bgghpmfgy24oodf; .ASPXAUTH=6BC2F53F9CA0CF5A437998B206B564B28B5AB362153E6E0629C9142F9E3A0285494F674716A126E4632A932BCE12CE094FE590911CE5E97EA42D0C610A44D8462A15BA9A54760883DDF712B5B199C136413667954F094FEBA2A57826BC84702A4D90D7382E360594ABC2F9EBDCEE696B4662077F; special=theId=1077b59a-100d-429b-b223-f8f0508fdc27&staffingId=77096&isBackupUser=False
In the second case, after opening the ReportViewer, our cookies are as follows:
theCulture=en-US; ASP.NET_SessionId=uhmquapd1bgghpmfgy24oodf; .ASPXAUTH=6BC2F53F9CA0CF5A437998B206B564B28B5AB362153E6E0629C9142F9E3A0285494F674716A126E4632A932BCE12CE094FE590911CE5E97EA42D0C610A44D8462A15BA9A54760883DDF712B5B199C136413667954F094FEBA2A57826BC84702A4D90D7382E360594ABC2F9EBDCEE696B4662077F; special=theId=1077b59a-100d-429b-b223-f8f0508fdc27&staffingId=77096&isBackupUser=False; /Reserved.ReportViewerWebControl.axd%3FOpType%3DSessionKeepAlive%26ControlID%3Dc3b959ab1a7c42e6a9fed5d2762a8c86_SKA=1
At which point we can no longer read them from WebApi. The method that returns the cookie in the WebAPI Controller is this:
public OurType GetApproverInfo()
{
OurType data = new OurType();
CookieHeaderValue cookie = Request.Headers.GetCookies("special").FirstOrDefault();
CookieState cookieState = cookie["special"];
data.Id = Guid.Parse(cookieState["theId"]);
data.StaffingId = Int32.Parse(cookieState["staffingId"]);
data.IsBackupUser = bool.Parse(cookieState["isBackupUser"]);
return data;
}
Anyone else seen something like this?
UPDATE: I've just learned that creating a cookie with a leading / in the name causes the same behavior in WebAPI.
What I see is that the ReportView is messing up the cookie. Probably you're setting up the cookie somewhere in the WebApi that has not the same pipeline execution sequence as the ReportView Handle.
Heres the WebApi life cycle: ASP.NET WEB API: HTTP MESSAGE LIFECYLE
But, you can override the ReportViewerServerConnection, using IReportServerConnection, and there persist yours cookie pattern.
Take a look here: Web.config Settings for ReportViewer
Another way should be setting up the cookie in a Custom IHttpModule, integrated into the ASP.NET pipe line, and then target both, WebApi and ReportView

How to receive XML in ASP.NET Web Service?

I have a quasi-RESTful ASP.NET web service that I wish to be able to post XML to. My method looks something like this:
[WebMethod(false, System.EnterpriseServices.TransactionOption.NotSupported)]
public void save(string saveXml)
{
XDocument saveXml = XDocument.Parse(saveXml);
....
When I try to post to that web service, I get the exception:
System.Web.HttpRequestValidationException: A potentially dangerous Request.Form
value was detected from the client...
Based on some searching, my understanding is that all requests to ASP.NET pages look for characters like "<" which are deemed dangerous (obviously this applies to my XML). This can be turned off easily for individual pages, but not web services. The only solution I have found involved changing the request validation mode in my web.config to "2.0". I don't want to change to an old version of something just because my one web service method doesn't work with the 4.0 version. Is there any way to disable this for my specific method? Thanks in advance.
The new 4.0 RequestValidation model is a bit pickier, but as long as your client sends the HTTP request Content-type header as text/xml instead of application/x-www-form-urlencoded it should pass (or bypass rather) ASP.NET RequestValidation.

Categories