Quantcast
Channel: Web API
Viewing all 4850 articles
Browse latest View live

ASP.NET Web API - Will there be a performance impact in using response.Content.LoadIntoBufferAsync().Wait()?

$
0
0

I had to catch the errors that occur during XML serialization (mostly due to invalid ASCII control codes), so I went on and replaced the controller endpoint as below.

Found the solution on how to do that here - http://stackoverflow.com/questions/16552715/how-do-i-trap-a-serializationexception-in-web-api/16554959#16554959

[DataContract(Name="ActivityData")]
[XmlRoot("Activity")]
public class ActivityData 
{
[DataMember]
public string Id { get; set; }

[DataMember]
public ActivityType type {get; set; }

....other Data members
}

**Before:**

[HttpGet]
public ActivityData GetActivityData(string startYear, string endYear)
{
ActivityData activityData = Repository.GetActivityData(startYear, endYear);

return activityData;
}

**After:**

[HttpGet]
public HttpReponseMessage GetActivityData(string startYear, string endYear)
{
try{ 
var responseContent = Repository.GetActivityData(startYear, endYear);
var response = Request.CreateReponse(HttpStatusCode.OK, responseContent);

//Below code ensures that any errors during serialization is caught. 
//But does it affect performance?
response.Content.LoadIntoBufferAsync().Wait(); 

return response;
}

catch(Exception ex){
logger.error(ex);
return Request.CreateResponse(HttpStatusCode.InternalServerError, ex);
} 
}

My question is that, will this have any imapct on the API's performance?

Does returning the object directly continuously 'stream' the data as it gets serialized and by Loading it into buffer, would the API serialize the entire object and then return it all together? or is just the same behaviour on both occasions?

I noticed the memory consumption go up when the code was hitting the return statement on both occasions. I would just like to know for sure that there wouldn't be any performance issues because of this change.

The returned XML document can be anywhere between a few MBs to a few hundred MBs of payload with number of rows ranging between hundreds and up to amillion rows. (depending on the start and end date), so is there a limit to the buffersize?

Thanks in advance.


Windows Auth on UI and API - Call API from javascript- Not working on Edge 38.14

OWIN middleware exceptions

$
0
0

Hi,

How can I handle exceptions which happen in OWIN middlewares?

From Web API 2.1 version there is global error handler, but it doesn't work for middlewares.

Oleg

How to integrate WebAPI with Paypal

$
0
0

Is it possible to integrate WebApi with paypal?

web api with multiple get and post type actions with custom action name without attribute routing usage

$
0
0

i have develop a sample web api controller with multiple get and post type action with custom action name using attribute routing.

now i like to know how could i develop the same without using attribute routing. just see my full working code and tell me can we have many action name in web api controller where i will specify custom action name but will not use attribute routing rather will use action name attribute.

see my code and remove attribute routing from there but all action should perform same way with custom action name. thanks

    [RoutePrefix("api/customer")]
    public class CustomerController : ApiController
    {
        static readonly ICustomerRepository repository = new CustomerRepository();

        [HttpGet, Route("GetAll")]
        public HttpResponseMessage GetAllCustomers()
        {
            IEnumerable<Customer> customers = repository.GetAll();
            if (customers == null)
            {
                var message = string.Format("No customers found");
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, message);
            }
            else
            {
                return Request.CreateResponse(HttpStatusCode.OK, customers);
            }


        }

        [HttpGet, Route("GetByID/{customerID?}")]
        public HttpResponseMessage GetCustomer(string customerID = null)
        {
            HttpResponseMessage retObject = null;
            bool IsError = false;
            Customer customer = null;
            var message="";

            if (string.IsNullOrEmpty(customerID))
            {
                 message = string.Format("Customer ID is empty or null");
                 HttpError err = new HttpError(message);
                 retObject = Request.CreateErrorResponse(HttpStatusCode.NotFound, err);
                 retObject.ReasonPhrase = message;
                IsError = true;
            }
            else
            {
                customer = repository.Get(customerID);
                if (customer.CustomerID == null)
                {
                     message = string.Format("Customer with id [{0}] not found", customerID);
                     HttpError err = new HttpError(message);
                     retObject = Request.CreateErrorResponse(HttpStatusCode.NotFound, err);
                     retObject.ReasonPhrase = message;
                     IsError = true;

                }
            }

            if (IsError)
                return retObject;
            else
                return Request.CreateResponse(HttpStatusCode.OK, customer);
        }

        [HttpGet, Route("GetByCountryName/{country?}")]
        public HttpResponseMessage GetCustomersByCountry(string country = null)
        {
            HttpResponseMessage retObject = null;

            if (!string.IsNullOrEmpty(country))
            {
                IEnumerable<Customer> customers = repository.GetAll().Where(
                    c => string.Equals(c.Country, country, StringComparison.OrdinalIgnoreCase));

                if (customers.Count() <= 0)
                {
                    var message = string.Format("No customers found by the country [{0}]", country);
                    HttpError err = new HttpError(message);
                    retObject = Request.CreateErrorResponse(HttpStatusCode.NotFound, err);
                    retObject.ReasonPhrase = message;
                }
                else
                {
                    retObject = Request.CreateResponse(HttpStatusCode.OK, customers);
                }
            }
            else
            {
                var message = string.Format("No country name provided");
                HttpError err = new HttpError(message);
                retObject = Request.CreateErrorResponse(HttpStatusCode.NotFound, err);
                retObject.ReasonPhrase = message;

            }
            return retObject;
        }

        // for adding new multiple customers
        [HttpPost, Route("AddCustomers")]
        public HttpResponseMessage PostCustomers(List<Customer> customer)
        {
            HttpResponseMessage response = null;
            var isError = repository.BulkAdd(customer);

            if (isError)
            {
                var message = string.Format("Due to error no customers added");
                HttpError err = new HttpError(message);
                response = Request.CreateErrorResponse(HttpStatusCode.ExpectationFailed, err);
                response.ReasonPhrase = message;
            }
            else
            {
                response = Request.CreateResponse<List<Customer>>(HttpStatusCode.Created, customer);
                response.ReasonPhrase = "Customers successfully added";
                //string uri = Url.Link("DefaultApi", new { customerID = customer.CustomerID });
                //response.Headers.Location = new Uri(uri);
            }

            return response;
        }

        // for adding new customer
        [HttpPost, Route("AddCustomer")]
        public HttpResponseMessage PostCustomer(Customer customer)
        {
            HttpResponseMessage response = null;
            customer = repository.Add(customer);

            if (customer == null)
            {
                var message = string.Format("Due to error no customer added");
                HttpError err = new HttpError(message);
                response = Request.CreateErrorResponse(HttpStatusCode.ExpectationFailed, err);
                response.ReasonPhrase = message;
            }
            else
            {
                response = Request.CreateResponse<Customer>(HttpStatusCode.Created, customer);
                response.ReasonPhrase = "Customer successfully added";
                //string uri = Url.Link("DefaultApi", new { customerID = customer.CustomerID });
                //response.Headers.Location = new Uri(uri);
            }

            return response;
        }

        // for updating existing customer based on customer id
        [HttpPost, Route("UpdateCustomer")]
        public HttpResponseMessage PutProduct(string customerID, Customer customer)
        {
            HttpResponseMessage response = null;
            customer.CustomerID = customerID;

            if (!repository.Update(customer))
            {
                var message = string.Format("Due to error no customer modified");
                HttpError err = new HttpError(message);
                response = Request.CreateErrorResponse(HttpStatusCode.ExpectationFailed, err);
                response.ReasonPhrase = message;
            }
            else
            {
                response = Request.CreateResponse<Customer>(HttpStatusCode.Created, customer);
                response.ReasonPhrase = "Customer successfully modified";
            }
            return response;
        }

        // for deleting existing customer based on customer id
        [HttpPost, Route("DeleteCustomer")]
        public HttpResponseMessage DeleteProduct(string customerID)
        {
            HttpResponseMessage response = null;
            Customer customer = repository.Get(customerID);
            if (customer == null)
            {
                var message = string.Format("No customer found by the ID {0}", customerID);
                HttpError err = new HttpError(message);
                response = Request.CreateErrorResponse(HttpStatusCode.ExpectationFailed, err);
                response.ReasonPhrase = message;
            }
            else
            {
                if(repository.Remove(customerID))
                {
                    response = Request.CreateResponse<Customer>(HttpStatusCode.Created, customer);
                    response.ReasonPhrase = "Customer successfully deleted";
                }
                else
                {
                    var message = string.Format("Due to some error customer not removed");
                    HttpError err = new HttpError(message);
                    response = Request.CreateErrorResponse(HttpStatusCode.ExpectationFailed, err);
                    response.ReasonPhrase = message;
                }
            }

            return response;
        }

    }

Discuss few advantages of attribute routing

$
0
0

i used attribute routing but still not very familiar with all the advantages of attribute routing.

[RoutePrefix("api/customer")]
    public class CustomerController : ApiController
    {
        static readonly ICustomerRepository repository = new CustomerRepository();

        [HttpGet, Route("GetAll")]
        public HttpResponseMessage GetAllCustomers()
        {
            IEnumerable<Customer> customers = repository.GetAll();
            if (customers == null)
            {
                var message = string.Format("No customers found");
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, message);
            }
            else
            {
                return Request.CreateResponse(HttpStatusCode.OK, customers);
            }


        }

    }

i just feel that we can give different name to action with attribute routing but beside this is there any other advantages are there?

if exist then please discuss the all advantages of attribute routing with example code. thanks

Enabling CORS

$
0
0

How to enable to CORS on server side(ASP.Net WebAPI) and client side (ajax call)?

Though it has been done this way it seems it is not working:

Any help would be appreciated.

public static class WebApiConfig
{  public static void Register(HttpConfiguration config)  {    // Other configuration omitted    config.EnableCors(new EnableCorsAttribute("domainname.com", "*", "*"));  }
}

Need help upgrading my Project

$
0
0

Hello,

I started a WEB API project with Visual Studio 2015 last year in June 2015. Since then the project has grown to be pretty massive and is currently being used in production serving clients. The biggest fear I currently have about the project is the fact that it is becoming out of date and we are having a difficult time upgrading the dependencies, and adding new "WCF Services" (SOAP APIs).

The biggest issue with upgrading is confusion on what is the greatest and latest framework to use. In addition, with our "telerik", "force" and "chargify" dependencies being essential for our business we want to upgrade without breaking them. When using .net core the don't seem to work with the project because they are dependent on .net. 

This is our "project.json" file.

{"webroot": "wwwroot","version": "1.0.0-*","dependencies": {"Microsoft.AspNet.Mvc": "6.0.0-beta5","Microsoft.AspNet.Server.IIS": "1.0.0-beta5","Microsoft.AspNet.Server.WebListener": "1.0.0-beta5","Microsoft.AspNet.StaticFiles": "1.0.0-beta5","System.Data.SqlClient": "4.0.0-beta-22816","System.IO.FileSystem": "4.0.0-beta-22816","System.ServiceModel": "1.0.0","Microsoft.Net.Http": "2.2.29","telerik.reporting": "9.2.15.1105","DeveloperForce.Force": "1.3.0","chargify": "1.1.5967.40624"
  },"commands": {"web": "Microsoft.AspNet.Hosting --server Microsoft.AspNet.Server.WebListener --server.urls http://localhost:5000"
  },"frameworks": {"dnx451": {"frameworkAssemblies": {"System.Runtime.Serialization": "4.0.0.0","System.ServiceModel": "4.0.0.0"
      }
    }
  },"exclude": ["wwwroot","node_modules","bower_components"
  ],"publishExclude": ["node_modules","bower_components","**.xproj","**.user","**.vspscc"
  ]
}


I would greatly appreciate any help/guidance on what to do with our project at this point. With all the new Microsoft tech coming out of beta we would like to be on the right path for long term support. 

Thank You!


WebAPI DocX to PDF conversion

$
0
0

Hi guys, I am currently stumped I have an API that I put together to take a file that gets posted to it in DOCX format and have it return a PDF, on my local machine it works without any problems, it creates the file on the file system in both scenarios but on my local test server it does not return the PDF, while my local machine does.

My server has Office 2013 installed, and so does my system. I wrote it to take files in a folder and convert them one by one, that works fine on the server, but I have no idea why it failing right now.

publicstringConvertFile(stringFileName){Word.Application W =newWord.Application();try{object misValue =System.Reflection.Missing.Value;
                W.Visible=false;
                W.DisplayAlerts=Word.WdAlertLevel.wdAlertsNone;object varMissing =Type.Missing;Word.Document D = W.Documents.Open(FileName,ReadOnly:true);string pdfFilename =FileName;string destination = pdfFilename.Substring(0, pdfFilename.LastIndexOf('.'))+".PDF";

                D.ExportAsFixedFormat(destination,Word.WdExportFormat.wdExportFormatPDF);
                D.Close(Word.WdSaveOptions.wdDoNotSaveChanges);return destination;}catch(Exception ex){return ex.InnerException.ToString();}finally{
                W.Quit();}}

Am I missing something?

With SOAPUI on my local machine it returns what I am looking for but from the local server it merely returns a hardly helpful message.

HTTP/1.1 500 Internal Server Error
Cache-Control: no-cache
Pragma: no-cache
Content-Type: application/json; charset=utf-8
Expires: -1
Server: Microsoft-IIS/10.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Wed, 21 Sep 2016 12:00:46 GMT
Content-Length: 36

{"Message":"An error has occurred."}

SoapDocumentMethod(OneWay = true) resulting in different HTTP status return depending upon SOAP version

$
0
0

If my method gets called with SOAP v1.1 (text/xml) the response is 202 which is what I expect based on the OneWay tag. If it gets called with SOAP v1.2 (application/soap+xml) the response code is 200.

Why?

Can't connect to GoogleMapsAPI when 'target machine actively refused it'?

$
0
0

I'm using the GoogleMapsAPI to return some location data which I am using in a ASP.Net web application. The application sends a postcode (similar to Zip code) to google which returns information relating to the location via Json. The application then uses the information to compare the distance with other locations which it has Geolocation data for on file.

The problem I'm having is that when I'm trying to request the Json data from the application I've recently started getting an exception "No connection could be made because the target machine actively refused it ...". I'm confused as the function was previously working although I haverecently moved the computer between offices so its on a new network point if that's relevant.

This is the code (the location is a class which stores information related to the location that's being investigated, an example postcode would be 'M13 9WL':

using (WebClient wc = new WebClient())
        {
            string SearchString = "https://maps.googleapis.com/maps/api/geocode/json?address=" + location.Postcode + "&key=AIzaSyAj0ZqfytaSX2B_Nm9MXRR63AL3uqWRgx4";
            var json = wc.DownloadString(SearchString);
            dynamic data = JObject.Parse(json);
            location.Latitude = data.results[0].geometry.location.lat;
            location.Longitude = data.results[0].geometry.location.lng;

        }

The exception occurs on the second line of code with the message "Unable to connect to the remote server" and inner exception message "No connection could be made because the target machine actively refused it XXX.XX.XXX.XXX:XXX"

When I run the same URL through the browser it works fine: https://maps.googleapis.com/maps/api/geocode/json?address=M13%209WL&key=AIzaSyAj0ZqfytaSX2B_Nm9MXRR63AL3uqWRgx4

Not sure what the problem is as the code did previously work. Any advice would be appreciated.

how to talk to elastic search using restful web api?

$
0
0

I want to create a web api which will talk to elastic search to get the data. I have tried it using getAsync() call.

It is running successfully, but when I am trying to send elastic search query through postAsync() call , it is always returning 'bad request ' as a response.

please suggest me the right way to do it?

Looking for walkthroughs on Autofac for Web API's with OWIN support

$
0
0

Hello, I just created a Web API and I'm going to need some help setting up IoC. Essentially what I want is to inject a service into a controller constructor.

My first shot at this was to use StructureMap but I learned that is not really designed for WebAPI's.

Now I'm looking at Autofac, but I'm finding very few guides out there that show how to integrate Autofac into a web API with OWIN for IoC support (there are a lot of guides, just not very many good ones).

Does anyone know of any good walkthroughs?

Thank you.

Web API System.net.http.formatting - JSON.NET - Builds well locally but fails on build server ",Version=4.5.0.0..''

$
0
0

I recently did some work on one of the older APIs and had to write some basic unit tests for the controller.

So, my controller test setup looks like this (followed by some simple tests)

using Newtonsoft.Json; (version 7.0.0 and was already part of the project)

[Setup] public void Init(){ usersController = new UsersController { Request = new HttpRequestMessage(), Configuration = new HttpConfiguration() }; XmlMediaTypeFormatter xmlFormatter = usersController.Configuration.Formatters.XmlFormatter; xmlFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/xml")); usersController.Configuration.Formatters.Clear(); usersController.Configuration.Formatters.Add(xmlFormatter); usersController.Request.Properties.Add(HttpPropertyKeys.HttpConfigurationKey, usersController.Configuration); }


The API project already uses NewtonSoft version 7.0.0. I had to reference it in my Test class as I have some tests that need to deserialize some JSON.

I have checked the version on `web.config` and `Myapiproject.csproj` as well, which looks like below and also app.config

**Web.config**<dependentAssembly><assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" /><bindingRedirect oldVersion="0.0.0.0-7.0.0.0" newVersion="7.0.0.0" /></dependentAssembly>

**MyAPIProject.csproj**

<Reference Include="Newtonsoft.Json, Version=7.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL"><SpecificVersion>False</SpecificVersion><HintPath>..\SharedProject\packages\Newtonsoft.Json.7.0.1\lib\net45\Newtonsoft.Json.dll</HintPath></Reference>


**App.config**
<dependentAssembly><assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" /><bindingRedirect oldVersion="0.0.0.0-7.0.0.0" newVersion="7.0.0.0" /></dependentAssembly>

Everything works well when built locally, but when built on the dev server, it fails with the below error

SetUp : System.IO.FileLoadException : Could not load file or assembly 'Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

[nunit2] at System.Net.Http.Formatting.JsonMediaTypeFormatter..ctor()
[nunit2] at System.Net.Http.Formatting.MediaTypeFormatterCollection.CreateDefaultFormatters()
[nunit2] at System.Web.Http.HttpConfiguration.DefaultFormatters()
[nunit2] at System.Web.Http.HttpConfiguration..ctor(HttpRouteCollection routes)

I searched for all libraries that are depending on NewtonSoft and found that Microsoft.AspNet.WebApi.Client.4.0.20710.0.nuspec had dependency on

<dependency id="Newtonsoft.Json" version="4.5.6" />

I'm certain that version 4.5.6 package no longer exists in the packages folder as it was removed and replaced by 7.0.0

I think `HttpConfiguration` or `MediaFormatter` has dependency on the older version of NewtonSoft and the build is failing because the version it's looking for is no longer available.

Also, I don't think I am referencing older version of NewtonSoftJson in my test class as I did an F12 on it and it showed it was version 7.0.0, and I think it's a a bit of a red herring that the project is failing on build server after I referenced JSON.NET on my test class.

How can I solve this without having to update NewtonSoftJson across the whole solution as that will have impacts on other projects? I don't think I can update the Web API package either.

I am sure it's similar to the issue here http://www.tomasvoracek.com/2015/07/could-not-load-file-or-assembly-newtonsoft-json-version4-5-0-0-cultureneutral-publickeytoken30ad4fe6b2a6aeed-or-one-of-its-dependencies/

Thanks

Are Web APIs the technology of today?

$
0
0

Are Web APIs the technology to use today instead of Web Services?


make web API in same or different project with MVC?

$
0
0

i want to make a web site in a form of web API 2 service that get consumed by a ASP.NET MVC site + android app + IOS app. should i make the web API project and the ASP.NET MVC projects as separate projects ?

WHY or why not ?

Web API Call send Excel file

$
0
0

How do I send an excel file via Web API using httpClient?

Currently my code is able to login to the companies Web API with credentials and receives a bearer token. Now that my app has the bearer token I want my code to send an excel file to the company via Web API call using httpClient. I have the url to post to.

I would like to use PostAsJsonAsync that will serialize the excel file to JSON. All the examples I find are passing in objects, like POCO, but my data is in an excel file, and the company I'm posting to is expecting an excel file that is serialized to JSON.  What is the code to serialize the excel file and post it via Web API call?

Here is one of the many links I found that shows PostAsjsonAsync but it doesn't use an excel file for the data, it shows creating an object and posting it. http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client

OWIN selfhosted Web Api doesn't response

$
0
0

Hi,

After one or two hours working API doesn't response. I can't stop windows service, only to kill process.

How can I investigate problem? 

Oleg

How to send xml to web api action

$
0
0

please give me a sample of web api action where i like to send person data in xml format.

give me two sample code one is web api action which accept person data and one is httpclient which will send person data in xml format ?

do i need to set anything to accept header for sending xml data ?

please help me with sample code.

Error page from Microsoft.Owin.Diagnostics

$
0
0

Hi,

I install package Microsoft.Owin.Diagnostics. Then I configured in server

  • appBuilder.UseWelcomePage("/welcomePage");
  • appBuilder.UseErrorPage(ErrorPageOptions.ShowAll);

when I started Web Api locally, I see http://http://localhost:12345/welcomepage

How and where I can see error page? How is it work? I couldn't find a documentation.

Oleg

Viewing all 4850 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>