Increasing Timeout Values in ASP.NET MVC 3 - asp.net-mvc-3

I have a JSON service that I'm exposing via ASP.NET MVC 3. This service is exposed as an Action on a Controller. I can successfully call the action. However, occasionally, the action takes too long to complete. Because of that, my caller fails due to a timeout. My question is, how do I change the timeout threshold's in ASP.NET MVC 3.

If you need do some task that you know can take a little while would be nice use AsyncControllers, and you can set diferent timeout betwen actions
for example
[AsyncTimeout(3000)] //timeout in miliseconds
public void DoTaskAsync(){
//something that takes a long time
AsyncManager.Parameters["result"] = contentresult; //Contentresult is your data result of process
}
public ActionResult DoTaskCompleted(String result){
return json(result);
}
http://msdn.microsoft.com/en-us/library/ee728598.aspx#Y4400 for details...
otherwise... HttpContext.Server.ScriptTimeout = 3000;

It depends what is timing out. If it's just the server response, I believe you can set it in the controller itself (in seconds):
HttpContext.Server.ScriptTimeout = XXX;
If it's something like the session or authentication timing out you will need to extend those values.

Related

Update clients in asp.net core 2.0 using SignalR

I am going through several examples on Asp.net Core WebAPI with SignalR where most of them are demonstrating simple chat application where this is what Hub returns:
return Clients.All.InvokeAsync("Send", message);
And this is how it gets called in Startup.cs
routes.MapHub<Chat>("chat");
The above example is good if message is not be send and updated to all the clients. In my case I have several APIs to be called whenever a data is changed:
Like Bank Transaction is done, I have to update ledger and several other reports at client side. But I don't see any option to pass Json.
Not finding exactly how to do this so that WebAPI gets refreshed everytime a change is there in the database.
As far as I understood, here "chat" is the endpoint which will be called from the frontend.
In this case what will happen to the endpoint I have created so far. Have a look at the below code example:
This api is to be called every time an entry is done:
public async Task<object> GetMarket(string marketshortcode)
{
Markets market = new Markets(marketshortcode);
return market.GetMarket();
}
and this the entry:
[Authorize]
[HttpPost]
public async Task<object> sellCurUser([FromBody] SellCur model)
{
if (model != null)
{
SellCurUser suser = new SellCurUser();
suser.sellcur = model;
my addition code...
}
return ....
}
There are several more endpoints which needs to be called at certain update/creation.
Now the point is how these apis will be changed or even not changed at all.
Do anyone have any example to understand it simply.

Web API 2 - Unity IOC - Shared instance per request variable

I am using web api with unity IOC.
web api client passes client-id in request header and based on this value dependencies are resolved to create a external dll's method instance.
creation of this instance take around 6-7 seconds which is creating performance issues in web api.
What I want is to prevent instance creation for call with same client-id in header.
This is how I have implemented till now:-
//========================== ArchiveFactory ==========================
ArchiveFactory archiverFactory = (HttpRequest httpRequest) =>
{
container.RegisterType<IArchive, Archive>("Archive",
new HierarchicalLifetimeManager(),
new InjectionConstructor(
new ResolvedParameter<IStoreClient>(),
Helper.GetArchiveContext(httpRequest))
);
return container.Resolve<IArchive>("Archive");
};
container.RegisterInstance(archiverFactory);
To be specific in my requirement - I am calling amazon services to retrieve images and there is a corporate dll which invokes amazon.
You can use caching mechanism at the controller/API layer(e.g Strathweb.CacheOutput.WebApi2) and you can decorate the controller method like this below. It's can cache based on parameter so if request comes in with same parameter, it will return results from cache.
[HttpGet]
[Route("")]
[CacheOutput(ServerTimeSpan = 60, ExcludeQueryStringFromCacheKey = true)]
public IHttpActionResult GetProducts(string clientId)
{
var product = new List<Product>();
return Ok(product);
}
Also, you might want to check the class constructor that you are trying to instantiate for issues that is taking it too slow. You may want to consider using lazy loading too if that will apply.

How to delay the response of my Web API

I am working on a Web API project and that has an Artist Web API Controller. On there, there is the api/artist method that is a GET for all artists.
When making the call to this method, I would like a 3 second delay before I serve the data, how can I achieve this?
CODE
public class ArtistController : ApiController
{
private GlContext db = new GlContext();
// GET api/Artist
public IQueryable<Artist> GetArtists()
{
return db.Artists;
}
}
I know that you wouldn't want to do this in a production environment, but I am playing with preloaders, and in order to test them properly I need to introduce this delay.
If it is just for testing you can always go for Thread.Sleep(3000)
http://msdn.microsoft.com/en-us/library/d00bd51t%28v=vs.110%29.aspx

Is it safe to use DateTime.Now as a default route value in ASP.NET MVC?

I have the following in an Area Registration of my ASP.NET MVC 3 project running on .NET Framework v4.0:
context.MapRoute(null,
"YardJob/{location}/{from}",
new { controller = "YardJob",
action = "List",
from = DateTime.Now });
My question is:
If the routing engine uses the default route value for 'from', will the List method on the controller always be invoked with the current date and time?
Is there any caching in the routing engine that may cause the default route value to be reused among requests?
Thanks,
As the accepted answer explains, this isn't possible. However, for the sake of completeness, here is how you would work around this:
Route:
context.MapRoute(null,
"YardJob/{location}/{from}",
new { controller = "YardJob",
action = "List",
from = UrlParameter.Optional }
);
Controller action:
public ActionResult List (string location, DateTime from)
{
if (from == null)
from = DateTime.Now;
}
the process of register the routes is executed when the application starts, so if you put DateTime.Now the default parameter for from field would be the time when the application starts, change only when the AppPool recycles
when application starts?
when the first resource (such as a page) in an ASP.NET application is requested. The Application_Start method in Global.asax is called only one time during the life cycle of an application. You can use this method to perform startup tasks such as loading data into the cache and initializing static values.
check out the life cicle

ASP.NET MVC3 app creating bad route value

OK, this may just me being ignorant, but I have the following route in my MVC3 application:
routes.MapRoute("Directory","{aid}/{controller}/{action}/{year}/{quarter}",
new { aid = "sf", controller = "Lobbyist", action = "Index",
year = CurrentYear(), quarter = CurrentQuarter() });
In my Global.asax.cs, I have these two methods:
public static int CurrentQuarter()
{
int quarter = 0;
//...use some internal business logic to determine the value of
//'quarter' based on the current date...
return quarter;
}
public static int CurrentYear()
{
return DateTime.Now.Year;
}
This code works great almost all the time. At one point in time, in our production environment (running IIS7), the route value for CurrentQuarter() became a value of zero, when it should have been 1, 2, 3, or 4. It works just fine in production except for that one point in time. An IISRESET 'fixed' the problem.
What I know:
At the time CurrentQuarter() was failing, CurrentYear() was still
returning correctly
The CurrentQuarter() method was not throwing an
exception which would have prevented setting the 'quarter' variable
The business logic which drives the CurrentQuarter() method works
for every date between DateTime.MinValue and DateTime.MaxValue
My question really gets down to is:
Is it BAD to call static methods to generate route values?
Is there a potential for the application to 'forget' the result of the static method, and cause it to return a garbage value? Could an application pool recycling cause this?
I'm sort of grasping at straws here!
Thanks for any advice.
I would not call static values here. I completely disagree with Igor above. Its not standard and is hard to track down where these values are coming from to someone that doesn't know the app. Call it either from your controller, or even better yet - a service layer (ie business logic) your controller calls to that gets this value.
A routes purpose is not to call a business method.
On the second question, if there is an app pool recycle, the value will simply be reset. However if multiple threads are calling into this method and potentially changing the value in the same method I would implement some locking in there to prevent updates from overlapping.
You should make the route values year and quarter optional, and provide default values for them in the Action method. I think this makes everything cleaner, and easier to maintain.
public class LobbyistController
{
public ActionResult Index(int? year, int? quarter)
{
if (!currentYear.HasValue)
{
currentYear = GetCurrentYear();
}
if (!currentQuarter.HasValue)
{
currentQuarter = GetCurrentQuarter();
}
// the rest
}
}

Resources