Lic
Lic

Reputation: 1957

C# Web Api xml save issue

I've got a strange behaviour with C# Web API and a save of xml. I've got this test class:

public class TestsApiController : ApiController
{
    [HttpGet]
    public HttpResponseMessage Test()
    {
        try
        {
            return Request.CreateResponse(System.Net.HttpStatusCode.OK, "OK!");
        }
        catch (Exception e)
        {
            return Request.CreateErrorResponse(System.Net.HttpStatusCode.BadRequest, e.Message);
        }

    }

    [HttpGet]
    public HttpResponseMessage Test2()
    {
        try
        {
            string path = System.IO.Path.Combine(HttpContext.Current.Server.MapPath("~/bin"),"Backup", string.Concat("test_", DateTime.Now.ToString("yyyyMddHHmmssffff"), ".xml"));

            System.IO.File.WriteAllText(path, "<?xml version=\"1.0\" encoding=\"UTF-8\"?><note><to>Tove</to><from>Jani</from><heading>Reminder</heading><body>Don't forget me this weekend!</body></note>");

            return Request.CreateResponse(System.Net.HttpStatusCode.OK, "Done!");
        }
        catch (Exception e)
        {
            return Request.CreateErrorResponse(System.Net.HttpStatusCode.BadRequest, e.Message);
        }

    }
}

Now the stranger thing: if I invoke Test after Test2 is isn't immediate but It took around 2s to finish. If I invoke Test another one it returns immediate. I'm trying with local server (IIS Express).

What's wrong?

I tried to save the xml file with XMLDocument.Save but the result not change.

I attach the timig from Google Chrome where You can see that TTFB is very high: Timing

Upvotes: 1

Views: 383

Answers (1)

Ashkan Nourzadeh
Ashkan Nourzadeh

Reputation: 1942

That's because you are writing to bin folder. It causes an application reload in IIS.
You can check this out by putting a break-point in Application_Start.

By changing the path to App_Data it works as expected. no delay.
HttpContext.Current.Server.MapPath("~/app_data")

Upvotes: 3

Related Questions