简体   繁体   中英

Redirecting an asp.net MVC URL to a specific controller/action/parameter using httpRedirect in web.config

I have a website hosted in Azure, which will be accessed with the URL https://abc.cloudapp.net/controller1/action1/parameter1

My Customer wants the following.

When we try to access the url " https://abc.cloudapp.net ", it should automatically redirect me to the actual url mentioned above for the website.

I want this to be achieved using the web.config. and I tried several combinations (Couple of those are listed below).

Combination 1:

<system.webServer>
  <rewrite>
    <rules>
        <rule name="Redirect to Full URL" stopProcessing="true">
            <match url=".*" />
            <conditions>
                <add input="{URL}" pattern="^abc.cloudapp.net$" />
            </conditions>
            <action type="Redirect" url="https://abc.cloudapp.net/controller1/action1/parameter1" redirectType="Permanent" />
        </rule>              
    </rules>
  </rewrite>
</system.webServer>

Combination 2:

<system.webServer>
  <rewrite>
    <rules>
        <rule name="Redirect to Full URL" stopProcessing="true">
            <match url="https://abc.cloudapp.net" />
            <action type="Redirect" url="https://abc.cloudapp.net/controller1/action1/parameter1" redirectType="Permanent" />
        </rule>              
    </rules>
  </rewrite>
</system.webServer>

None of these combinations have worked. I had posted a workaround below for this problem. However, I need some quick help in this for a permanent solution. I still need help on this, can some one help please.

I had found a workaround for this.

When we use the url " https://abc.cloudapp.net ", using the default route config we can set this to go to action1 in controller1.

Then in "action1" of "controller1" if we see that the "parameter1" is null (must be delared as a nullable type), we need to initialize the parameter1 to a known value and redirect to the same "action1" in "controller1"

public ActionResult Index(int? parameter1)
{
  if(string.IsNullOrEmpty(parameter1)
    return RedirectToAction("action1", "controller1", new {@parameter1 = "knownValue"});
  else
  {
    //whatever action you wanted to do based on value in parameter1
  }
}

However this whole method calls for hard coding, We are assigning a know value to the paramter1. If there is a change in this value, we need to change the code Hence I do not recommend this. However for now I have used this workaround. I still need a proper solution around this problem.

MY R & D Continues... ... ... ... ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM