I am trying to change my old domain to new one and I have huge data on my website. I need to change only my domain by url rewriting.
When I request:
www.myolddomain.net/article/seo-friendly-url-for-this-article
I need to have a permanent (301) redirect to:
www.mynewdomain.com/article/seo-friendly-url-for-this-article
How ca I do this in asp.net core?
Have you considered URL Rewriting Middleware?
It's pretty simple.
Drop a IISUrlRewrite.xml file in the root of your application folder. Mark it as "Content" and "Copy to output directory" set to true, looks like this in your csproj
<ItemGroup>
<Content Include="IISUrlRewrite.xml">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
Add following content in the file
<rewrite>
<rules>
<rule name="Host replace - Old to new" stopProcessing="true">
<match url=".*" />
<conditions>
<add input="{HTTP_HOST}" pattern="www\.myolddomain\.net" ignoreCase="true" />
</conditions>
<action type="Redirect" url="https://www.mynewdomain.com{REQUEST_URI}" redirectType="Permanent" appendQueryString="true" />
</rule>
</rules>
</rewrite>
Register the URL rewrite module in the Configure method of your Startup.cs file
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
// Irrelevant code omitted
using (var iisUrlRewriteStreamReader = File.OpenText(Path.Combine(env.ContentRootPath, "IISUrlRewrite.xml")))
{
var options = new RewriteOptions().AddIISUrlRewrite(iisUrlRewriteStreamReader);
app.UseRewriter(options);
}
// Irrelevant code omitted
}
Related
I’m trying to remove the response Server header from an Azure Web App ( with an ASP Net core application )
After many tries of changing the web.config and removing the header in app code using a middleware, Microsoft doesn’t give up and set the response header to Server: Microsoft-IIS/10.0 :)
The problem appears only when I’m trying to access the server on http (not https). Response code from the server is 301, and this is the only response that has the Server header.
Checking the logs I was not able to find any request to http://, and perhaps this is why I’m not able to remove header, because the request is not process in my application code.
A solution that I’m thinking is to disable the azure HTTPS only and do the redirect to https in my code (I tested and is working - server header is removed)
Is there another workaround without disabling the HTTPS only option?
Here is what I tried
Startup.cs
public void Configure(IApplicationBuilder app)
{
app.Use(async (context, next) =>
{
context.Response.Headers.Add("server", string.Empty)
}
app.UseHttpsRedirection();
}
web.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<httpRuntime enableVersionHeader="false" />
<!-- Removes ASP.NET version header. -->
</system.web>
<system.webServer>
<httpProtocol>
<customHeaders>
<remove name="Server" />
<remove name="X-Powered-By" />
</customHeaders>
<redirectHeaders>
<clear />
</redirectHeaders>
</httpProtocol>
<security>
<requestFiltering removeServerHeader="true" />
<!-- Removes Server header in IIS10 or later and also in Azure Web Apps -->
</security>
<rewrite>
<outboundRules>
<rule name="Change Server Header"> <!-- if you're not removing it completely -->
<match serverVariable="RESPONSE_Server" pattern=".+" />
<action type="Rewrite" value="Unknown" />
</rule>
</outboundRules>
</rewrite>
</system.webServer>
</configuration>
UPDATE
When the URL of http:// is requested, IIS will process it, this time without code. So we can't control it by the code, we can only set it on the server, such as some scripts or tools. But on Azure, we have no way to directly operate as a physical server, so after exploration, I suggest that Front Door can be used to deal with this problem. Hiding server information through proxy should be a better way.
After my test, the server information is hidden, you can refer to this document . We can see from the picture that there is no 301 redirect request, and no server information in other requests.
PREVIOUS
You need to modify Global.asax.cs and Web.config file in your program.
In Global.asax.cs.
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
MvcHandler.DisableMvcResponseHeader = true;
PreSendRequestHeaders += Application_PreSendRequestHeaders;
}
protected void Application_PreSendRequestHeaders(object sender, EventArgs e)
{
//HttpContext.Current.Response.Headers.Remove("Server");
HttpContext.Current.Response.Headers.Set("Server","N/A");
}
}
And In Web.config.
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" >
</modules>
<httpProtocol>
<customHeaders>
<remove name="X-Powered-By" />
</customHeaders>
</httpProtocol>
</system.webServer>
Then u can deploy your app. After the above code modification, access to the interface or static resources can see that the server information is modified, of course, it can also be deleted by Remove.
You also can handle special event by http status code.
protected void Application_PreSendRequestHeaders(object sender, EventArgs e)
{
//HttpContext.Current.Response.Headers.Remove("Server");
int StatusCode= HttpContext.Current.Response.StatusCode;
// handle like http status code 301
HttpContext.Current.Response.Headers.Set("Server","N/A");
}
I am trying to receive a parameter by URL, but if this parameter has a '+' I do not receive it, for example:
www.domain.com/api/controller/Demo?guid=123+456
[HttpPost("Demo")]
public IActionResult PostData([FromQuery]string guid, Model model)
{
Inside the function, the guid value is 123 456
if this parameter has a '+' I do not receive it, for example: www.domain.com/api/controller/Demo?guid=123+456. Inside the function, the guid value is 123 456
To achieve your requirement, you can try following approaches:
Approach 1: manually replace the + sign to %2B while client make request to your API action.
Approach 2: encode query string guid=123+456 by using URL Rewriting Middleware, like below.
In Startup.cs
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
//...
using (StreamReader iisUrlRewriteStreamReader =
File.OpenText("IISUrlRewrite.xml"))
{
var options = new RewriteOptions()
.AddIISUrlRewrite(iisUrlRewriteStreamReader);
app.UseRewriter(options);
}
//...
}
In IISUrlRewrite.xml
<?xml version="1.0" encoding="utf-8" ?>
<rewrite>
<rules>
<rule name="TESTURL">
<match url="api/your_controller_name/Demo" />
<conditions>
<add input="{QUERY_STRING}" pattern="guid=([0-9]+\+[0-9]+)" />
</conditions>
<action type="Rewrite" url="api/your_controller_name/Demo?guid={UrlEncode:{C:1}}" appendQueryString="false" />
</rule>
</rules>
</rewrite>
Test Result
I want my Asp.net core application to be configured to use external providers only, let's say Facebook only. In other words I don't want my users to have the ability to create an account with a password etc.
How can I modify the default Asp.net core with individual accounts template that is generated by Visual Studio to safely remove such capability of creating local user accounts?
Thanks.
I'm using the .UseRewriter() middleware to allow me to redirect to /Error for the Identity pages that don't apply to my application (I only allow Github authentication and no local registration)
public static class IisRewriterConfigurationExtensions
{
public static IApplicationBuilder UseIisRewriter(this IApplicationBuilder applicationBuilder)
{
using (var iisUrlRewriteStreamReader = File.OpenText("iis-application-route-rewrites.xml"))
{
var options = new RewriteOptions()
.AddIISUrlRewrite(iisUrlRewriteStreamReader);
applicationBuilder.UseRewriter(options);
}
return applicationBuilder;
}
}
Then I call app.UseIisRewriter(); in Startup.Configure().
My iis-application-route-rewrites.xml looks like this
<?xml version="1.0" encoding="utf-8" ?>
<rewrite>
<rules>
<rule name="Redirect from Identity Forgot Password">
<match url="^Identity/Account/ForgotPassword" />
<action type="Redirect" url="Error?id=404" redirectType="Permanent" />
</rule>
<rule name="Redirect from Identity Reset Password">
<match url="^Identity/Account/ResetPasswordConfirmation" />
<action type="Redirect" url="Error?id=404" redirectType="Permanent" />
</rule>
<!-- More rules -->
</rules>
</rewrites>
In my Login.cshtml.cs I removed all the request handlers that I no longer wanted users to have access to.
Is there are way to serve gzip static cotent when using self host environment to publish an ASP.NET Core website?
[Edit 2016-11-13]
There is another way to serve gzipped files that replaces steps 2 and 3. It's basically quite the same idea, but there is a nuget package that does it all for you readily available. It basically checks if the is .gz or .br file that matches the requested one. If it exists it returns it with the appropriate headers. It does verify that the request has a header for the corresponding algorithm. Github code if you want to compile it yourself is here.
There is also an issue to support that in the official repository, so I really hope Microsoft will have the standard plugin to do that, since it's rather common and logical to use that nowadays.
I think I have found the most optimized way of serving the compressed content. The main idea is to pre-compress the files and since the default ASP.NET 5 way is to use gulp to build js, it is as easy to do as this:
1. Add a gulp step to gzip the bundled libraries:
gulp.task("buildApplication:js", function () {
return gulp.src(...)
...
.pipe(gzip())
...
});
This will produce something like libraries.js.gz in your bundles folder
2. Refernce the libraries.js.gz instead of libraries.js in the cshtml file
3. Amend the static file handler to fix the returned headers
We need to add Content-Encoding and change the Content-Type from default application/x-gzip to application/javascript because not all browsers are smart enough to read js properly from x-gzip
app.UseStaticFiles(new StaticFileOptions
{
OnPrepareResponse = context =>
{
if (headers.ContentType.MediaType == "application/x-gzip")
{
if (context.File.Name.EndsWith("js.gz"))
{
headers.ContentType = new MediaTypeHeaderValue("application/javascript");
}
else if (context.File.Name.EndsWith("css.gz"))
{
headers.ContentType = new MediaTypeHeaderValue("text/css");
}
context.Context.Response.Headers.Add("Content-Encoding", "gzip");
}
}
});
Now all there is no CPU cycles to waste to gzip the same content all the time and it's the best possible performance in serving the files. To improve it even further all of js has to be bunlded and minified before gzipping. Another upgrade is to set CacheControl max age in the same OnPrepareResponse to cache for one year and add asp-append-version="true" in the cshtml.
P.S. If you will host behind IIS you might need to turn off the static compression of js and css not to double compress, I am not sure how it will behave in this situation.
This is a fixed version of method 3 from Ilyas answer that works with ASP.NET Core 1 RTM, and it serves pre-zipped javascript files:
app.UseStaticFiles(new StaticFileOptions
{
OnPrepareResponse = context =>
{
IHeaderDictionary headers = context.Context.Response.Headers;
string contentType = headers["Content-Type"];
if (contentType == "application/x-gzip")
{
if (context.File.Name.EndsWith("js.gz"))
{
contentType = "application/javascript";
}
else if (context.File.Name.EndsWith("css.gz"))
{
contentType = "text/css";
}
headers.Add("Content-Encoding", "gzip");
headers["Content-Type"] = contentType;
}
}
});
#Ilya's Answer is very good but here are two alternatives if you are not using Gulp.
ASP.NET Core Response Compression Middleware
In the ASP.NET Core BasicMiddlware repository, you can find (at time of writing) a pull request (PR) for Response Compression Middleware. You can download the code and add it to you IApplicationBuilder like so (at time of writing):
public void Configure(IApplicationBuilder app)
{
app.UseResponseCompression(
new ResponseCompressionOptions()
{
MimeTypes = new string[] { "text/plain" }
});
// ...Omitted
}
IIS (Internet Information Server)
IIS (Internet Information Server) has a native static file module that is independent of the ASP.NET static file middleware components that you’ve learned about in this article. As the ASP.NET modules are run before the IIS native module, they take precedence over the IIS native module. As of ASP.NET Beta 7, the IIS host has changed so that requests that are not handled by ASP.NET will return empty 404 responses instead of allowing the IIS native modules to run. To opt into running the IIS native modules, add the following call to the end of Startup.Configure.
public void Configure(IApplicationBuilder app)
{
// ...Omitted
// Enable the IIS native module to run after the ASP.NET middleware components.
// This call should be placed at the end of your Startup.Configure method so that
// it doesn't interfere with other middleware functionality.
app.RunIISPipeline();
}
Then in your Web.config use the following settings to turn on GZIP compression (Note that I included some extra lines to compress things like .json files which are otherwise left uncompressed by IIS):
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.webServer>
<!-- httpCompression - GZip compress static file content. Overrides the server default which only compresses static
files over 2700 bytes. See http://zoompf.com/blog/2012/02/lose-the-wait-http-compression and
http://www.iis.net/configreference/system.webserver/httpcompression -->
<!-- minFileSizeForComp - The minimum file size to compress. -->
<httpCompression directory="%SystemDrive%\inetpub\temp\IIS Temporary Compressed Files" minFileSizeForComp="1024">
<scheme name="gzip" dll="%Windir%\system32\inetsrv\gzip.dll" />
<dynamicTypes>
<add mimeType="text/*" enabled="true" />
<add mimeType="message/*" enabled="true" />
<add mimeType="application/x-javascript" enabled="true" />
<!-- Compress XML files -->
<add mimeType="application/xml" enabled="true" />
<!-- Compress JavaScript files -->
<add mimeType="application/javascript" enabled="true" />
<!-- Compress JSON files -->
<add mimeType="application/json" enabled="true" />
<!-- Compress SVG files -->
<add mimeType="image/svg+xml" enabled="true" />
<!-- Compress RSS feeds -->
<add mimeType="application/rss+xml" enabled="true" />
<!-- Compress Atom feeds -->
<add mimeType="application/atom+xml" enabled="true" />
<add mimeType="*/*" enabled="false" />
</dynamicTypes>
<staticTypes>
<add mimeType="text/*" enabled="true" />
<add mimeType="message/*" enabled="true" />
<add mimeType="application/x-javascript" enabled="true" />
<add mimeType="application/atom+xml" enabled="true" />
<add mimeType="application/xaml+xml" enabled="true" />
<!-- Compress ICO icon files (Note that most .ico files are uncompressed but there are some that can contain
PNG compressed images. If you are doing this, remove this line). -->
<add mimeType="image/x-icon" enabled="true" />
<!-- Compress XML files -->
<add mimeType="application/xml" enabled="true" />
<add mimeType="application/xml; charset=UTF-8" enabled="true" />
<!-- Compress JavaScript files -->
<add mimeType="application/javascript" enabled="true" />
<!-- Compress JSON files -->
<add mimeType="application/json" enabled="true" />
<!-- Compress SVG files -->
<add mimeType="image/svg+xml" enabled="true" />
<!-- Compress EOT font files -->
<add mimeType="application/vnd.ms-fontobject" enabled="true" />
<!-- Compress TTF font files - application/font-ttf will probably be the new correct MIME type. IIS still uses application/x-font-ttf. -->
<!--<add mimeType="application/font-ttf" enabled="true" />-->
<add mimeType="application/x-font-ttf" enabled="true" />
<!-- Compress OTF font files - application/font-opentype will probably be the new correct MIME type. IIS still uses font/otf. -->
<!--<add mimeType="application/font-opentype" enabled="true" />-->
<add mimeType="font/otf" enabled="true" />
<!-- Compress RSS feeds -->
<add mimeType="application/rss+xml" enabled="true" />
<add mimeType="application/rss+xml; charset=UTF-8" enabled="true" />
<add mimeType="*/*" enabled="false" />
</staticTypes>
</httpCompression>
<!-- Enable gzip and deflate HTTP compression. See http://www.iis.net/configreference/system.webserver/urlcompression
doDynamicCompression - enables or disables dynamic content compression at the site, application, or folder level.
doStaticCompression - enables or disables static content compression at the site, application, or folder level.
dynamicCompressionBeforeCache - specifies whether IIS will dynamically compress content that has not been cached.
When the dynamicCompressionBeforeCache attribute is true, IIS dynamically compresses
the response the first time a request is made and queues the content for compression.
Subsequent requests are served dynamically until the compressed response has been
added to the cache directory. Once the compressed response is added to the cache
directory, the cached response is sent to clients for subsequent requests. When
dynamicCompressionBeforeCache is false, IIS returns the uncompressed response until
the compressed response has been added to the cache directory.
Note: This is set to false in Debug mode to enable Browser Link to work when debugging.
The value is set to true in Release mode (See web.Release.config).-->
<urlCompression doDynamicCompression="true" doStaticCompression="true" dynamicCompressionBeforeCache="false" />
</system.webServer>
</configuration>
You could implement an action filter that compresses the contents of the response if the client supports it.
Here is an example from MVC5. You should be able to modify that to work with MVC 6:
http://www.erwinvandervalk.net/2015/02/enabling-gzip-compression-in-webapi-and.html
I’m working on url routing
I want to redirect page without change url.
When type url www.example.com/Default.aspx that time url show as same but return page Home/Index (Controller/Action)
I want to redirect page with actual url.
And second require is when type www.example.com/Default.aspx that time show url in address bar Home/Index and return this page
How to possible please describe in details.
Thank you in advance.
I think that the cleanest way of doing this is to use the URL Rewrite module in IIS. However, as you asked about doing it in MVC I'll cover that first:
To achieve 1 (when /default.aspx is requested return /home/index.
Add the following to your route table:
routes.MapRoute("HomepageDefault", "default.aspx", new { controller = "Home", action = "Index" });
To achieve 2, you need to redirect the request - easiest way to do this will be to set a route up to an actionresult, and then redirect it:
routes.MapRoute("RedirectRoute", "default.aspx", new { controller = "Home", action = "Redirect" });
And then in the ActionResult:
public ActionResult Redirect()
{
return RedirectToAction("Index", "Home");
}
The alternative is to do this with the URL Rewrite Module in IIS.
To achieve 1:
<rewrite>
<rules>
<rule name="Rewrite rule">
<match url="^default.aspx$" />
<action type="Rewrite" url="/home/index" />
</rule>
</rules>
</rewrite>
To achieve 2:
<rewrite>
<rules>
<rule name="redirect">
<match url="^default.aspx$" />
<action type="Redirect" url="/home/index" />
</rule>
</rules>
</rewrite>