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

The 'ObjectContent`1' type failed to serialize the response body for content type 'text/xml; charset=utf-8'

$
0
0

I get normal response from API when I request content type 'text/json and the problem when I request content type 'text/xml; I get this message An error has occurred.The 'ObjectContent

1' type failed to serialize the response body for content type 'text/xml; charset=utf-8'.</ExceptionMessage><ExceptionType>System.InvalidOperationException</ExceptionType><StackTrace /><InnerException><Message>An error has occurred.</Message><ExceptionMessage>There was an error generating the XML document.</ExceptionMessage><ExceptionType>System.InvalidOperationException</ExceptionType><StackTrace> at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, String encodingStyle, String id) at System.Net.Http.Formatting.XmlMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, HttpContent content) at System.Net.Http.Formatting.XmlMediaTypeFormatter.WriteToStreamAsync(Type type, Object value, Stream writeStream, HttpContent content, TransportContext transportContext, CancellationToken cancellationToken) --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Web.Http.WebHost.HttpControllerHandler.&lt;WriteBufferedResponseContentAsync&gt;d__1b.MoveNext()</StackTrace><InnerException><Message>An error has occurred.</Message><ExceptionMessage>The type System.Collections.Generic.List
1[[testtransotels.data.cities, testtransotels, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] may not be used in this context.System.InvalidOperationException at System.Xml.Serialization.XmlSerializationWriter.WriteTypedPrimitive(String name, String ns, Object o, Boolean xsiType) at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterObject.Write1_Object(String n, String ns, Object o, Boolean isNullable, Boolean needType) at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterObject.Write2_anyType(Object o)

my code as you see

private datacontext db =new datacontext();publicobjectPost([FromBody]RequestRequest){return db.Student;}publicclassStudent{[DataMember]publicstringStudentID{ get;set;}[DataMember]publicstringStudentName{ get;set;}[DataMember]publicstringStudentCode{ get;set;}}

How to get json when testing web api action by fiddler

$
0
0

this is how my action look like

        [HttpGet]
        [Route("GetByID/{customerID}")]
        public HttpResponseMessage GetCustomer(string customerID)
        {
            Customer customer = repository.Get(customerID);
            if (customer == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
            Response response = new Response(1, "SUCCESS", customer);
            return Request.CreateResponse(HttpStatusCode.OK, response);

        }
   public class Response
    {
        int ResponseCode;
        string ResponseMessage;
        object ResponseData;
        public Response(int code, string message, object data)
        {
            ResponseCode = code;
            ResponseMessage = message;
            ResponseData = data;
        }
    }

this way i am returning data to client return Request.CreateResponse(HttpStatusCode.OK, response);

but the problem is fiddler is just showing this symbol {} instead of data ? why ?

how we can see my json at client side from ResponseData property ?

please guide me. thanks

How to call my web api action by http cient

$
0
0
<div class="post-text" itemprop="text">

my web api action return data bit different way. see my action code

[HttpGet]
[Route("GetByID/{customerID}")]
public HttpResponseMessage GetCustomer(string customerID)
{
    Customer customer = repository.Get(customerID);
    if (customer == null)
    {
        throw new HttpResponseException(HttpStatusCode.NotFound);
    }
    Response response = new Response(1, "SUCCESS", customer);
    return Request.CreateResponse(HttpStatusCode.OK, response);

}

my Response class code in which i wrapped the data as object and return to client.

   public class Response
    {
        int ResponseCode;
        string ResponseMessage;
        object ResponseData;
        public Response(int code, string message, object data)
        {
            ResponseCode = code;
            ResponseMessage = message;
            ResponseData = data;
        }
    }

now i like to know how could i call my web api by

http client
and extract customer data and show the customer data through
datagridview
.

</div>

Using OData with Repository Pattern

$
0
0

I have some new requirements for paging, sorting and filtering in my ASP.NET Web API Web application which I had previously designed to use a standard RESTful interface.  I am wrapping all of my Entity Framework operations currently using a Repository pattern along with using a DI container such as Unity to inject the appropriate Repositories.

However, I am thinking that I may have to use ODataControllers to meet the paging, sorting and filtering requirements of my application, however, this implementation seems very tightly coupled to hooking into the Entity Framework Data Model.

Is there a way to use OData with Web API without tightly coupling it to my Entity Framework Data Model and still retain the abstraction to use my Repository classes instead?  

Please advise.  Any code samples/examples would be greatly appreciated.

Thanks.

Issue for Deserialize object

$
0
0

Hi,

I am using Newtonsoft.Json package to deserialize the json object, But my json object contains the special characters like "\" and "'" (apos) with in it. for example in "container_type_str" contains \' which cause the exception.  

{"generated" : "2015-12-03T13:33+0000","event" : {"id" : 128454,"shipment_id" : 52354,"severity" : 1, "created" : "2015-11-30T10:52+0000"
},"shipment" : {"id" : 52354, "number" : "MSCUBH188555","weight" : null,"container_type_str" : "20\' DRY VAN", 
}
}

  var eventMessage = JsonConvert.DeserializeObject<CSharpObject>(message);



I am getting following exception. 

After parsing a value an unexpected character was encountered: D. Path 'shipment.container_type_str', line 1, position 1376.
Newtonsoft.Json.JsonReaderException: After parsing a value an unexpected character was encountered: D. Path 'shipment.container_type_str', line 1, position 1376.
at Newtonsoft.Json.JsonTextReader.ParsePostValue()
at Newtonsoft.Json.JsonTextReader.Read()
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateObject(Object newObject, JsonReader reader, JsonObjectContract contract, JsonProperty member, String id)
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)

How to return my custom class from my web api action

$
0
0

suppose this is my class which i like to return from my action

    public class Response
    {
        public bool IsSuccess { get; set; }
        public string Message { get; set; }
        public object ResponseData { get; set; }

        public Response(bool status, string message, object data)
        {
            IsSuccess = status;
            Message = message;
            ResponseData = data;
        }
    }

OR

    public class Response<T>
    {
        public bool IsSuccess { get; set; }
        public string Message { get; set; }
        public IEnumerable<T> ResponseData { get; set; }

        public Response(bool status, string message, IEnumerable<T> data)
        {
            IsSuccess = status;
            Message = message;
            ResponseData = data;
        }
    }

now this way i am wrapping output into response class and return from web api action

[HttpGet, Route("GetAll")]
public HttpResponseMessage GetAllCustomers()
{
    var Response=new Response(true, "SUCCESS", repository.GetAll());
    return Response;
    return Request.CreateResponse(HttpStatusCode.OK, Response);
    HttpResponseMessage response = Request.CreateResponse<Response>(HttpStatusCode.OK, Response);
    return response;
}

but json is not coming to client. where i made the mistake in code ?

i need to get json when i will invoke the above action from fiddler. please guide me how to fix the above code a result right json of Response class should return to client?

please give fresh and rectified working code copy of above one. thanks

How to return error message in details to client from web api action

$
0
0

how could i return error message to client using

HttpResponseMessage
? suppose i am sending customer data from client to web api and web api is validating and if data is not right say suppose customer name is empty or null or email is wrong then we have to return error message to client..........tell me how could i do that
HttpResponseMessage
class
?

tell me best practice to return error message in details to http client from web api action.

thanks

How to read web api response with HttpClient c#

$
0
0

i am fairly new in web api. i have developed small web api which has few action and return my custom class called Response.

Response class look like

public class Response
{
    bool IsSuccess=false;
    string Message;
    object ResponseData;

    public Response(bool status, string message, object data)
    {
        IsSuccess = status;
        Message = message;
        ResponseData = data;
    }
}

my web api with few actions

[RoutePrefix("api/customer")]publicclassCustomerController:ApiController{staticreadonlyICustomerRepository repository =newCustomerRepository();[HttpGet,Route("GetAll")]publicResponseGetAllCustomers(){returnnewResponse(true,"SUCCESS", repository.GetAll());}[HttpGet,Route("GetByID/{customerID}")]publicResponseGetCustomer(string customerID){Customer customer = repository.Get(customerID);if(customer ==null){thrownewHttpResponseException(HttpStatusCode.NotFound);}returnnewResponse(true,"SUCCESS", customer);//return Request.CreateResponse(HttpStatusCode.OK, response);}[HttpGet,Route("GetByCountryName/{country}")]publicIEnumerable<Customer>GetCustomersByCountry(string country){return repository.GetAll().Where(
            c =>string.Equals(c.Country, country,StringComparison.OrdinalIgnoreCase));}}

now where i stuck is that i do not know how to read response data return from web api actions and extract json from my response class. after getting json how could i

deserialize

that json to customer class.

this way i am calling my web api function.

privatevoid btnLoad_Click(object sender,EventArgs e){HttpClient client =newHttpClient();
    client.BaseAddress=newUri("http://localhost:8010/");// Add an Accept header for JSON format.  //client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));// List all Names.  HttpResponseMessage response = client.GetAsync("api/customer/GetAll").Result;// Blocking call!  if(response.IsSuccessStatusCode){Console.WriteLine("Request Message Information:- \n\n"+ response.RequestMessage+"\n");Console.WriteLine("Response Message Header \n\n"+ response.Content.Headers+"\n");}else{Console.WriteLine("{0} ({1})",(int)response.StatusCode, response.ReasonPhrase);}Console.ReadLine();}

just guide me sample code

1) how to get response class which web api action returns at client side

2) how could i extract json from response class

3) how to deserialize the json to customer class at client side

thanks


WebAPI:How to read message from HttpResponseMessage class at client side

$
0
0

below is a sample action which is returning

HttpResponseMessage

and if any error occur then this way web api action returning error message and status code to client side return

Request.CreateErrorResponse(HttpStatusCode.NotFound, message);

.

[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);
    }
}

when i am invoking action by http client then i am not getting message in

ReasonPhrase

property. just tell me what is the right way to read message at client side which is passing like this way

return Request.CreateResponse(HttpStatusCode.OK, customers);

here is my client side code

private async void btnFind_Click(object sender, EventArgs e)
{
    var fullAddress = baseAddress + "api/customer/GetByID/"+txtFind.Text;
    Customer _Customer = null;

    using (var client = new HttpClient())
    {
        using (var response = client.GetAsync(fullAddress).Result)
        {
            if (response.IsSuccessStatusCode)
            {
                var customerJsonString = await response.Content.ReadAsStringAsync();
                _Customer = JsonConvert.DeserializeObject<Customer>(customerJsonString);
            }
            else
            {
                Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
            }
        }
    }

    if (_Customer != null)
    {
        var _CustList = new List<Customer> { _Customer };
        dgCustomers.DataSource = _CustList;
    }

}
response.ReasonPhrase

not holding the message which i am passing from action. so may be i am not doing things to read message. please tell me what to change in my code to read the message. thanks

In web APi Return in json

$
0
0

this is my code

[System.Web.Http.Route("JobApi/getDataForAngularGrid")]
[System.Web.Mvc.HttpGet]
public JsonResult getDataForAngularGrid()
{
JobBL objbl = new JobBL();
var Statelist = objbl.GetAllState(31);
return Json(Statelist, JsonRequestBehavior.AllowGet);

}

But getting error in JsonRequestBehavior.AllowGet how to solve the problem 

How to know the web api project version ?

$
0
0

which area i should look for to know the version ?

if i want to work with web api version 2 from VS2013 IDE then what i need to do.........give a details instruction.

thanks

WebAPI V1 4.0.30506 incorrect on Nuget? Really Version 4.0.20918

$
0
0

I'm looking for the last Webapi v1 for Framework 4.0, as per Nuget there should be a version 4.0.3056.

Downloading the 4.0.3 package and looking at the properties of the Dll's in the lib folder shows versions of 4.0.20918 which is from the prior release.

I binary compare shows them as identical. Seems the fact the entire 4.0.3 stack is is 4.0.2 (Core\Client\Http)

Anybody know how to get the DLL's or build them from source?

See Packages (rename to zip and compare)

https://www.nuget.org/packages/Microsoft.AspNet.WebApi.SelfHost/4.0.30506

 and

https://www.nuget.org/packages/Microsoft.AspNet.WebApi.SelfHost/4.0.20918

Kind Regards,

Mike

How to deserialize data at client side when web api action return data in xml format

$
0
0

1) first situation is say my web api action return data in xml format. so tell me when i will call that web api action with httpclient then how could i deserialize that customer xml data to my customer class at client side ?

suppose this is my web api actions

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

        [HttpGet, Route("GetAll")]
        public HttpResponseMessage GetAllCustomers()
        {
            //return new Response(true, "SUCCESS", repository.GetAll());
            return Request.CreateResponse(HttpStatusCode.OK, new Response(true, "SUCCESS", repository.GetAll()));
        }

        [HttpGet, Route("GetByID/{customerID}")]
        public Response GetCustomer(string customerID)
        {
            Customer customer = repository.Get(customerID);
            if (customer == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
            return new Response(true, "SUCCESS", customer);
            //return Request.CreateResponse(HttpStatusCode.OK, response);
        }

        [HttpGet, Route("GetByCountryName/{country}")]
        public IEnumerable<Customer> GetCustomersByCountry(string country)
        {
            return repository.GetAll().Where(
                c => string.Equals(c.Country, country, StringComparison.OrdinalIgnoreCase));
        }

        public HttpResponseMessage PostCustomer(Customer customer)
        {
            customer = repository.Add(customer);
            var response = Request.CreateResponse<Customer>(HttpStatusCode.Created, customer);

            string uri = Url.Link("DefaultApi", new { customerID = customer.CustomerID });
            response.Headers.Location = new Uri(uri);
            return response;
        }

        public void PutProduct(string customerID, Customer customer)
        {
            customer.CustomerID = customerID;
            if (!repository.Update(customer))
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
        }

        public void DeleteProduct(string customerID)
        {
            Customer customer = repository.Get(customerID);
            if (customer == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
            repository.Remove(customerID);
        }
    }
public class Response
    {
        bool IsSuccess = false;
        string Message;
        object ResponseData;

        public Response(bool status, string message, object data)
        {
            IsSuccess = status;
            Message = message;
            ResponseData = data;
        }
    }
   public class Customer
    {
        public string CustomerID { get; set; }
        public string CompanyName { get; set; }
        public string ContactName { get; set; }
        public string ContactTitle { get; set; }

        public string Address { get; set; }

        public string Region { get; set; }

        public string PostalCode { get; set; }
        public string City { get; set; }
        public string Country { get; set; }
        public string Phone { get; set; }
        public string Fax { get; set; }
    }

now calling like this way

            var baseAddress = "http://localhost:8010/api/customer/GetAll";
            using (var client = new HttpClient())
            {
                using (var response = await client.GetAsync(baseAddress))
                {
                    if (response.IsSuccessStatusCode)
                    {


                    }
                    else
                    {
                        Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
                    }
                }
            } 

when response.IsSuccessStatusCode is true then tell me how could i read the response and extract the customer data from response class.

just give me sample code of HttpClient which show me how to deserialize response and customer class. please include sample code which i can use. thanks

Best way to return error message from Web API

UnitTest for WebApi Failed in VSTS

$
0
0

I have written simple unit test for my rest api which is passed succesfully in my local machine but if i am running it in visual studio team services(vsts)  it fails with following error message....Please help

2016-08-27T08:51:16.5118002Z ##[error]Error Message:
2016-08-27T08:51:16.5118002Z ##[error] Test method MyWebApi.Controllers.Tests.EmployeeInfoApiControllerTests.GetTest threw exception:
2016-08-27T08:51:16.5128011Z ##[error]System.IO.FileNotFoundException: Could not load file or assembly 'MyWebApi, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.WRN: Assembly binding logging is turned OFF.
2016-08-27T08:51:16.5128011Z ##[error]To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1.
2016-08-27T08:51:16.5128011Z ##[error]Note: There is some performance penalty associated with assembly bind failure logging.
2016-08-27T08:51:16.5138007Z ##[error]To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].
2016-08-27T08:51:16.5138007Z ##[error]
2016-08-27T08:51:16.5138007Z ##[error]Stack Trace:
2016-08-27T08:51:16.5148007Z ##[error] at MyWebApi.Controllers.Tests.EmployeeInfoApiControllerTests.GetTest()
2016-08-27T08:51:16.5558013Z Results File: C:\a\1\TestResults\buildguest_TASKAGENT5-0001 2016-08-27 08_51_16.trx
2016-08-27T08:51:16.5568211Z Total tests: 2. Passed: 1. Failed: 1. Skipped: 0.
2016-08-27T08:51:16.5578015Z ##[error]Test Run Failed.
2016-08-27T08:51:16.5588008Z Test execution time: 1.1132 Seconds
2016-08-27T08:51:16.6128007Z ##[error]System.Exception: VSTest Test Run failed with exit code: 1
2016-08-27T08:51:16.6258010Z Publishing Test Results...


How copy manually the web api (mvc 4) pre-installed files from other PC to my home PC in web developer 2010

$
0
0

I cannot apply this asp.net mvc 4 module (http://www.microsoft.com/en-us/download/details.aspx?id=30683) to my web developer 2010. So I hope already installed

files copying would help (on another computer there is VS 2010 full so I can apply this module). F.e. I simply copied extension folder from another PC to my home PC and the PM library works now that demand sinternet connection. Where to find web api

mvc 4 installation -- in web developer folder itself (I have it f.i. on disk E) or in system disk folder where .net framework is installed?

Claims aware application in VS 2015

How to Launch API from MVC in Core

$
0
0

I have an application with an MVC site and a Web API. I'm setting up a demo and I want to start/run the API from the MVC app and then show using a client (Postman) to interact. Right now I'm just directing to the Get and returning some Json. It opens a download browser and as long as I keep that open I can use the API. The problem is that is that holds my MVC up, and when I close the browser it ends the debug session.

Is there a way to run the API "inside" the MVC project and have it return to the MVC side when I end the API side?

webapi + CORS: POST works, PUT does not

$
0
0

Hi,

I have a problem accessing a webapi-REST-service with CORS. What I've done so far:

  • installed Microsoft.AspNet.Cors V 5.2.3 via NuGet,
  • called config.EnableCors() in the "Register" method of WebApiConfig,
  • set the attribute [EnableCors("*", "*", "*")] on the controller.

A CORS-POST call (from an angular2-app) with headers "content-type: application/json" and "accept: application/json" succeeds. The corresponding Fiddler protocol lists the preflight-OPTIONS request from the browser (IE11) followed by the POST request.

If I issue a PUT request from the very same application, fiddler just lists the OPTIONS request with the servers answer "404 No action was found on the controller ... that matches the request". The PUT request uses the same headers as the POST request.

When I issue the PUT request from swagger/swashbuckle, everything works fine (just not being a CORS request). The controller is an ODataController.

Can anyone explain, what I'm doing wrong. If you need further info to solve this problem, please let me know.

Thanks in advance
Jürgen

What is the usage of generic controller in web api

$
0
0

please discuss with example code how to design generic controller in web api. also share knowledge in what kind of scenario people think to write generic controller in web api.

please give me situation for which generic controller would be best solution to done the jobs. thanks

Viewing all 4850 articles
Browse latest View live


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