Answered Requests are permitted between...

raysefo

Well-known member
Joined
Feb 22, 2019
Messages
362
Programming Experience
10+
Hello,

I have an asp.net web API. The client wants me to add a valid time interval (09:00 - 21:30) in order to accept requests. Let's say if a request comes at 08:00, it will be denied with a message saying Requests are permitted between 9:00 AM and 21:30 PM. I am planning to implement this logic in the global.asax as follows, but I am not sure if there is a better way.

C#:
ublic class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            
            GlobalConfiguration.Configure(WebApiConfig.Register);
          
        }

        protected void Application_BeginRequest()
        {
            

            if (CheckTime9To2130())
            {
                //do something
            }
            else
            {
                Response.StatusCode = 429;
                Response.Write("Requests are permitted between 9:00 AM and 21:30 PM");
                Response.End();
            }
        }

        private bool CheckTime9To2130()
        {
            var h = DateTime.Now.TimeOfDay.Hours;
            var m = DateTime.Now.TimeOfDay.Minutes;

            if ((9 <= h && h <= 21) || (h == 21 && m <= 30))
            {
                return true;
            }

            return false;
        }
    }

What if the client wants to change the time interval? I need to change it in the code base and deploy it to the server. So I think I need to put those times into an appsettings of config. But it still has a cost, when I change it on the config, the IIS will be restarted right? So keeping those times in the database seems to be the only solution? What are your suggestions?
 
The query to see if they are over their daily limit seems overly complex to me, but that's likely a different topic, and besides, I'm not a SQL expert.

Anyway, the rest looks good to me (beyond whitespace and coding style preferences/issues).
 
Can I return Web.Http.Results instead of HttpResponseMessage? Any way to convert the response to web.http.results @Skydiver ?

C#:
var response = new HttpResponseMessage
                {
                    StatusCode = (HttpStatusCode)429,
                    ReasonPhrase = "Invalid Request Time",
                    Content = new StringContent("Requests are permitted between " + WebConfigurationManager.AppSettings["TimeStart"].ToString() + " AM and " + WebConfigurationManager.AppSettings["TimeEnd"].ToString() + " PM.")

                };
 
Like this? It gave error, didn't convert.
C#:
actionContext.Response = new System.Web.Http.Results.ResponseMessageResult(new HttpResponseMessage
               {
                   StatusCode = (HttpStatusCode)429,
                   ReasonPhrase = "Invalid Request Time",
                   Content = new StringContent("Requests are permitted between " + WebConfigurationManager.AppSettings["TimeStart"].ToString() + " AM and " + WebConfigurationManager.AppSettings["TimeEnd"].ToString() + " PM."));
               }
 
It may help if you actually told us what error you were getting...
 
Actually I am not getting any errors. I told a client wants me to add limits and I implemented filters. In the filters, I am returning HttpResponseMessage. This client says he wants to get a response as I return in the actions,

C#:
return new System.Web.Http.Results.ResponseMessageResult(
                    Request.CreateErrorResponse((HttpStatusCode)222, new HttpError("No Results Found")));
 
It gave error, didn't convert.
Actually I am not getting any errors.
Lets assume I put the Jackie Chan WHAT gif here....

Seriously, how do you determine you get an error, but not get an error and say that in the same breath? What are you doing? Or do you not know again? Or is this where we play the game of fix my problem for me while i answer with indirect answers to the questions I was asked?

On a side note, you are attempting to send back the wrong error code. That will only mislead your clients users of their application by providing them with headers for an error that is unrelated to the reason you're wanting to provide an error for. I think I must be throwing this link at you for fun at this stage : Hypertext Transfer Protocol (HTTP) Status Code Registry - Where in that link does it say that 222 is the correct error header to send back a 429 response?

429 would be more accurate. However, if you look at the HttpStatusCode., you will see that the responses you can use are limited. But these can be overridden by Casting 429, and provide a suitable message which would be more applicable. Instead of sending back "No Results Found", which I assume is wrong, and should be stating that the user has reached the query limit and specify a timeout period in which they can retry.

Either you are smart enough to cast your custom error or you've copied code from somewhere on the net without properly checking the documentation for the code you are using. I also don't see where you've implemented an interface which actually would make returning the below HttpResponse relatively easy. Further, upon searching up on MSDN for Action Results in Web API 2 - ASP.NET 4.x I've noticed that my browser has previously been on this link before, and I've previously told you to implement this very interface earlier in your project, and here i am again. You also had Skydiver's previous link which also included an example of how to use this interface.

What you should be doing is using the debugger and stepping into the code to identify what the code is doing, and when you do that, research each of your problematic methods on MSDN, and then come back to the forum and report the behaviour your debugger is reporting to you, and tell us which behaviour you want to achieve instead. It is also imperative to report exactly what the error is or what didn't "convert". Rather than trying to have us run around troubleshooting an issue which clearly requires your inspection. We are not querying your API, you are; and therefore, we can't precisely replicate your problem. You need to put more effort into explaining your issue regarding the problem you're experiencing. Otherwise you will likely find your support will quickly diminish. My patience are already running tin, given the information you've already been given and yet disregarded. I'm getting deja vu.

C#:
return new HttpResponseMessage(HttpStatusCode.{Your Error here});
 
@Sheepings Yet again writing for writing instead of understanding what I am asking, assume I put Homer Simpson gif hitting head on the wall.
  1. I have a filter attribute
  2. OnAuthorization I am returning HttpResponseMessage
C#:
public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            //Check Request Start-End Period
            if (!CheckRequestTime())
            {
                var response = new HttpResponseMessage
                {
                    StatusCode = (HttpStatusCode) 429,
                    ReasonPhrase = "Invalid Request Time",
                    Content = new StringContent("Requests are permitted between " +
                                                WebConfigurationManager.AppSettings["TimeStart"].ToString() +
                                                " AM and " + WebConfigurationManager.AppSettings["TimeEnd"].ToString() +
                                                " PM.")
                

                };

                actionContext.Response = response;
                

            }
        }

3. A Client wants me to return ResponseMessageResult​
C#:
{
    "Message": "Requests are permitted between 11:00 AM and 22:30 PM."
}
All I am asking if it is possible to return ResponseMessageResult instead of HttpResponseMessage in the OnAuthorization? Is it clear for you now?​
This below solved my problem;​
C#:
Content = new StringContent("{\"Message\":\"Requests are permitted between " +
                                                WebConfigurationManager.AppSettings["TimeStart"].ToString() +
                                                " AM and " + WebConfigurationManager.AppSettings["TimeEnd"].ToString() +
                                                " PM.\"}", System.Text.Encoding.UTF8, "application/json"),
 
Last edited:
@Sheepings Yet again writing for writing instead of understanding what I am asking, assume I put Homer Simpson gif hitting head on the wall.
Firstly. No. I am not writing for writing, but writing for the sake of explanation. An explanation which you don't seem to be getting into your thick skull. Anyone who reads this thread can see clearly that you are in over your head once again. And they can also see that we have spent time pointing out where you are going wrong. Yet, once more, you come back and spit rubbish code at us which shows no attempt to implement the interface which I and @Skydiver told you to implement. Had you taken your head out of your ass and read the links and information which we both sent you, you would find two working examples demonstrating how you can achieve what you are needing to do; which is essentially converting from a HttpResponseMessage to a IActionResult.

Secondly. You'll have to forgive my frustration. Because It's clear you are nothing more than a help vampire. You're also looking for a handout which you won't be getting from me. You refuse to read the relevant documentation and information. And you refuse to debug your own code.

You write your own code on this bored and show some bloody effort. You should be grateful for the help you've already received, because it's as much as you're going to get from me currently. Until you make the required recommended changes to your code, you will get no further replies. This is also not the first topic where I've told you that you should be using this interface. That's the same link I gave you before, except you skipped out on read towards the Interface itself.

Lastly. If you are to stupid to implement an interface, then we are incapable of helping you. Visual Studio can generate the interface for you. The documentation clearly states that you can do as you are asking, but you're required to use the interface provided. So please enlighten me where you have implemented any such interface in the above cluster of irrelevant code?

All I am asking if it is possible to return ResponseMessageResult instead of HttpResponseMessage
Yes.
This below solved my problem;
I pity your client, and good luck.
 

Latest posts

Back
Top Bottom