How can I accept email address as a route value?

帅比萌擦擦* 提交于 2019-12-23 18:53:27

问题


How can I have this simple Route:

http://domain.com/Calendar/Unsubscribe/my@email.com

I have a route that looks like:

routes.MapRoute(
    "Unsubscribe", 
    "Calendar/Unsubscribe/{subscriber}", 
    new { 
       controller = "Calendar", 
       action = "Unsubscribe", 
       subscriber = "" }
);

and my action is:

public ActionResult Unsubscribe(string subscriber)
{
    ...
}

Without any parameters, like http://domain.com/Calendar/Unsubscribe/ works fine, but soon I add the email, I get a 404 page :(

Is there any trick I have to do?

Thank you


回答1:


Try adding a trailing slash to the url http://domain.com/Calendar/Unsubscribe/my@email.com/ without changing the routing rules.

If you still want to avoid adding the trailing slash and you have URL Rewrite available, you could add a rewrite rule into the web.config

<system.webServer>
  <rewrite>
    <rules>
      <rule name="Fix Unsubscribe emails route" stopProcessing="true">
        <match url="^(Calendar/Unsubscribe/.*@.*)$" />
        <action type="Rewrite" url="{R:1}/" />
      </rule>
    </rules>
  </rewrite>
</system.webServer>

You could also write a better regular expression than the one I provided for the sake of readability.

You could also try to reorder your route params like /Calendar/my@email.com/Unsubscribe so that the e-mail is not the last param.




回答2:


I think this should do it.

routes.MapRoute(
"Unsubscribe", 
"Calendar/Unsubscribe/{subscriber}", 
   new { 
   controller = "Calendar", 
   action = "Unsubscribe"
   }
    new { subscriber =  @"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" }
);



回答3:


I tried it in default home controllor and working with no error

_http://localhost:64718/home/index/a.b@email.com

Welcome to ASP.NET MVC! a.b@email.com

public ActionResult Index(string id)    
{    
    ViewModel.Message = "Welcome to ASP.NET MVC!   " + id;    
    return View();    
}

No changes in defaultroute-MVC.

do you have any other routes defined before Unsubscribe which will match same route




回答4:


Try removing the default empty string for subscriber.




回答5:


The @ symbol is a reserved character in URLs:

http://en.wikipedia.org/wiki/Percent-encoding

Try encoding it; Thusly, your new url would be:

http://domain.com/Calendar/Unsubscribe/my%40email.com



回答6:


you don't need to add new rote! I tried it in Asp.Net Mvc4 application without any new routes and it worked. you can check email in Unsubscribe Method. I think it's better to do that.

good luck!



来源:https://stackoverflow.com/questions/4307358/how-can-i-accept-email-address-as-a-route-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!