Encode Email to pass to Web.API

2019-04-07 13:18发布

I am needing to send an email address to a Web.Api get method. I need to check to see if the email address exists in our system before allowing someone to sign up for a new account.

My first thought was to encode the email address and then decode it once it was inside the Get Action

The URL looks something like this http://mysite/Api/RTSCredit/jharding%40email.com

However, This always errors with a 404 response

Here is the WebApiConfig.cs

 config.Routes.MapHttpRoute(
      name: "DefaultApi",
      routeTemplate: "api/{controller}/{emailAddress}",
      defaults: new { id = RouteParameter.Optional }
  );

When I send in a simple string http://mysite/Api/RTSCredit/someemail

It hits the Get action like I would prefer, but obviously can't return a useful value.

Here is the Get Action

[HttpGet]
public HttpResponseMessage Get([FromUri] string emailAddress)
{
    using (IRtsCreditDal rtsCreditDal = new RtsCreditDal())
    {
        var listOfExistingUsers = rtsCreditDal.GetUsersByEmail(emailAddress);
        if (listOfExistingUsers == null || listOfExistingUsers.Count == 0)
        {
            return Request.CreateResponse(HttpStatusCode.NotFound, "not found");
        }
        else
        {
            return Request.CreateResponse(HttpStatusCode.OK); 
        }
    }
  }

What adjustments do I need to make in order to pass an email to this Action?

As I've been playing further, it doesn't seem to like the period in the URL. I could easily do something to replace that character but it feels like a hack.

3条回答
冷血范
2楼-- · 2019-04-07 13:30

Try adding a trailing / at the end of the email reaching from the client:

http://localhost:8800/api/users/user@gmail.com/
查看更多
Animai°情兽
3楼-- · 2019-04-07 13:33

Try to decode your string parameter value.

String newEmailAddress = HttpUtility.HtmlDecode(emailAddress);

That would replace characters like '%' by the characters of your original text.

查看更多
可以哭但决不认输i
4楼-- · 2019-04-07 13:36

Change your default route back to

config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

Remove the [FromUri] attribute from the Action, then you should be able to call your action using the url suggested by Maess:

/mysite/Api/RTSCredit?emailAddress=jharding%40email.com
查看更多
登录 后发表回答