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

ORA- 12154: TNS:could not resolve the connect identifier specified ASP.NET Web API

$
0
0

I am trying to host the Web API that was published in the DEV server in to the TEST server.I used the published method as File System in DEV and copied those folder in to Test server and tried to create the new Website in the IIS. So in the IIS, I see the connection string

<connectionStrings><add name="ProDataConnection" connectionString="Data Source=ABC;User Id=ABCD;Password=ABCDE;pooling=true;min pool size=5;Max Pool Size=60" providerName="Oracle.DataAccess.Client" /></connectionStrings>

Also I did check the tnsnames.ora has the connection details.I did create the Environment Variable TNS_ADMIN as

enter image description here

enter image description here

But when I test the API in the Fiddler it gives me

{"Message":"An error has occurred.","ExceptionMessage":"The 'ObjectContent1' type failed to serialize the response body for content type 'application/json; charset=utf-8'.","ExceptionType":"System.InvalidOperationException","StackTrace":null,"InnerException":{"Message":"An error has occurred.","ExceptionMessage":"ORA-12154: TNS:could not resolve the connect identifier specified","ExceptionType":"Oracle.ManagedDataAccess.Client.OracleException","StackTrace":" at OracleInternal.ConnectionPool.PoolManager 3.Get(ConnectionString csWithDiffOrNewPwd, Boolean bGetForApp, String affinityInstanceName, Boolean bForceMatch)\r\n at OracleInternal.ConnectionPool.OraclePoolManager.Get(ConnectionString csWithNewPassword, Boolean bGetForApp, String affinityInstanceName, Boolean bForceMatch)\r\n at OracleInternal.ConnectionPool.OracleConnectionDispenser 3.Get(ConnectionString cs, PM conPM, ConnectionString pmCS, SecureString securedPassword, SecureString securedProxyPassword)\r\n at Oracle.ManagedDataAccess.Client.OracleConnection.Open()\r\n at ProvantisStudyData.Controllers.OracleDataTableJsonResponseConverter.WriteJson(JsonWriter writer, Object value, JsonSerializer serializer)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeConvertable(JsonWriter writer, JsonConverter converter, Object value, JsonContract contract, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)\r\n at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value, Type objectType)\r\n at Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value, Type objectType)\r\n at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding effectiveEncoding)\r\n at System.Net.Http.Formatting.JsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding effectiveEncoding)\r\n at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStreamAsync(Type type, Object value, Stream writeStream, HttpContent content, TransportContext transportContext, CancellationToken cancellationToken)\r\n--- End of stack trace from previous location where exception was thrown ---\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Web.Http.WebHost.HttpControllerHandler.d__1b.MoveNext()","InnerException":{"Message":"An error has occurred.","ExceptionMessage":"ORA-12154: TNS:could not resolve the connect identifier specified","ExceptionType":"OracleInternal.Network.NetworkException","StackTrace":" at OracleInternal.Network.AddressResolution..ctor(String TNSAlias, String instanceName)\r\n at OracleInternal.Network.OracleCommunication.DoConnect(String tnsDescriptor)\r\n at OracleInternal.ServiceObjects.OracleConnectionImpl.Connect(ConnectionString cs, Boolean bOpenEndUserSession, String instanceName)"}}}

server local folder image severing to android code as web api service

$
0
0

Hello,

I have been trying to implement severing image to android , from local folder of server . when I access my web api it has to server an image to android code .  i tired with multiple code available on internet, but none of them working perfectly as desired  .

Thanks,

Shuhaib

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 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>

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)

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 to return customer data with HttpResponseMessage

$
0
0
            HttpResponseMessage r = new HttpResponseMessage();
            r.StatusCode = HttpStatusCode.OK;
            r.ReasonPhrase = "SUCCESS";

now how could i pass my customer object by HttpResponseMessage class to client side ?

one way is return Request.CreateResponse(HttpStatusCode.OK, customers);

suppose if i do not want to return response this way Request.CreateResponse(HttpStatusCode.OK, customers); rather i want to create instance of HttpResponseMessage and initialize few property and then return. so tell me ow could i pass my customer object by HttpResponseMessage class to client side ?

thanks

Regarding web api and send/receive to and from json to action

$
0
0

I just add the following in App_Start/WebApiConfig.cs class in my MVC Web API project.

config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html")

i just like to verify one things that when we set that response will be always in json always. so when we send json from client to action over get or post method then do i need to again specify that i am sending json to action like below way ?

HttpClient client =newHttpClient();
client.BaseAddress=newUri("http://localhost:38762/api/customer/AddCustome");
client.DefaultRequestHeaders.Accept.Add(newMediaTypeWithQualityHeaderValue("application/json"));

please guide me that we need to said to web api for request and response both case that i am sending json or i want json as response ?


How to pass customer object to web api action

$
0
0

i am trying to perform crud operation by web api. so i pass customer json from client to web api action.

this is my json which i passed from client to action.

{"CustomerID":"James","CompanyName":"jame pvt","ContactName":"James","ContactTitle":"Sr Developer","Address":"Salt lake","Region":"sect-1","PostalCode":"700009","City":"kolinara","Country":"India","Phone":"033-8547-4789","Fax":"033-8547-4781"}

my web api action looks as below

[RoutePrefix("api/customer")]publicclassCustomerController:ApiController{[HttpPost,Route("AddCustomer")]publicHttpResponseMessagePostCustomer(Customer customer){
                customer = repository.Add(customer);var response =Request.CreateResponse<Customer>(HttpStatusCode.Created, customer);
                response.ReasonPhrase="Customer successfully added";string uri =Url.Link("DefaultApi",new{ customerID = customer.CustomerID});
                response.Headers.Location=newUri(uri);return response;}}

this way i try to call action from httpclient from winform apps

private async void btnAdd_Click(object sender,EventArgs e){Customer oCustomer =newCustomer{CustomerID="James",CompanyName="James pvt",ContactName="James",ContactTitle="Sr Developer",Address="Salt lake",Region="sect-1",PostalCode="700009",City="Kolinara",Country="India",Phone="033-8547-4789",Fax="033-8547-4781"};var fullAddress ="http://localhost:38762/api/customer/AddCustomer";try{
                using (var client =newHttpClient()){var serializedCustomer =JsonConvert.SerializeObject(oCustomer);var content =newStringContent(serializedCustomer,Encoding.UTF8,"application/json");

                    using (var response = client.PostAsync(fullAddress, content).Result){if(response.IsSuccessStatusCode){var customerJsonString = await response.Content.ReadAsStringAsync();//_Customer = JsonConvert.DeserializeObject<IEnumerable<Customer>>(customerJsonString);}else{Console.WriteLine("{0} ({1})",(int)response.StatusCode, response.ReasonPhrase);var dict =JsonConvert.DeserializeObject<Dictionary<string,string>>(response.Content.ReadAsStringAsync().Result);MessageBox.Show(dict["Message"]);}}}}catch(HttpRequestException ex){// catch any exception here}}

this is the error message i got when i do the same from fiddler. the error msg is :

{"Message":"The request contains an entity body but no Content-Type header. The inferred media type 'application/octet-stream' is not supported for this resource.","ExceptionMessage":"No MediaTypeFormatter is available to read an object of type 'Customer' from content with media type 'application/octet-stream'.","ExceptionType":"System.Net.Http.UnsupportedMediaTypeException","StackTrace":" at System.Net.Http.HttpContentExtensions.ReadAsAsync[T](HttpContent content, Type type, IEnumerable

1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)\r\n at System.Net.Http.HttpContentExtensions.ReadAsAsync(HttpContent content, Type type, IEnumerable
1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)\r\n at System.Web.Http.ModelBinding.FormatterParameterBinding.ReadContentAsync(HttpRequestMessage request, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)"}

now please tell me what is wrong in my code for which i am getting error.

thanks

web api security for use by salesforce

$
0
0

Hello,

I am new to web api and new to salesforce.  We are writing some services to be used by salesforce connect.  As part of the salesforce setup you can provide credentials, odata security info, anon access,(what we have today and it works) etc to allow access to the web api services.  

I have done some looking at securing these services but looking for a good example of how to secure them for use by salesforce?  Anyone out there know of a good tutorial that can explain this simply with examples?

Thanks.

Web api listener accept json similar to below example

$
0
0

I am new to c# and web api . Suppose my web api listener want to accept below structured data how should I write the c# method

{
"Patient": {
"UniqueID": "WH555444",
"Name": {
"LastName": "Doe",
"FirstName": "John",
"Middle": "Frank"
},
"OrderId":"86023",
"Labs":[{

"Setid": "2",
"valuetype": "ED",
"ObservationIdentifier": "6690-2^WBC^LN",

"ObservationValue": "8.08",

"ObservResultStatus": "F",

"ReferencesRange": "4.00-10.00",
"AbnormalFlags": "A",

"Units": "10*9/L",

"UserDefinedAccessChecks": "E"
},
{

"Setid": "2",
"valuetype": "ED",
"ObservationIdentifier": "6690-2^WBC^LN",

"ObservationValue": "8.08",

"ObservResultStatus": "F",

"ReferencesRange": "4.00-10.00",
"AbnormalFlags": "A",

"Units": "10*9/L",

"UserDefinedAccessChecks": "E"
}]
}
}

Web API Authentication

$
0
0

Hi,

    I am using Web API for web project in which UI is done by angular js. I want to add Authentication. Can you say, which way is best and how to do it?

Thanks in advance.

When to enable Cross Origin Resource Sharing (CORS) in web api

$
0
0

i develop a web api running and publish in IIS in pc1 and when i call that web api from pc2 then it works but i did not enable any CORS.......so how it is working ?

so tell me in what kind of scenario CORS is not required and when required. thanks

How create asp.net web api on web developer 2008/2010 or sharpdevelop

$
0
0

I have no opportunity to use full visual studio 2010, 2012 or later for simple use of web api. So I would like to use it in other way.

So I would like to know does web developer 2008 or 2010 support web api projects ? Since what version or year did web api appeared?

If I would like to use sharpdevelop 4.3, how to use web api? If I have downloaded such project as -- Getting Started with ASP.NET Web API (Tutorial Sample).zip,

how to open and run it succesfully in Sharpdevelop?

I have read about using empty asp.net web-page template for web api - how can I connect to apicontroller, routing?

Handling exception thrown during controller Initialize override.

$
0
0

I have a base controller class that's inherited by several controller classes. The base class overrides Initialize to do some preparation so that any action handler will have access to some important basic data when it begins to execute.

My question is: if an exception is thrown within this method then what is the preferred way to handle and send a response back to client?

This exception will be thrown (or rather might be thrown) before any action method has yet been invoked and so the Request member is null at that point.

Within action handlers themselves I have this:

            catch (Exception e)
            {
                HttpResponseMessage message = Request.CreateErrorResponse(HttpStatusCode.BadRequest, e);
                throw new HttpResponseException(message);
            }

but because Request is null in the Initialize override this cannot work, beside I don't know if throwing a new HttpResponseException within Initialize is the right thing to do.

Thanks


what to set in action level to return json?

$
0
0

We set some instruction in webapi config file to return json in response. So tell me can we set some instruction in action level to return json instead of webapi config file.

web api client and json

$
0
0
What kind of instruction we need to send from web api client to say i need response in json format from web api.

Web api and MediaType

$
0
0

just see two set of code and tell me both will do the same job?

just add the following in App_Start/WebApiConfig.cs class in my MVC Web API project.

config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html")

1) i guess the above instruction will inform web api to return only response in json formar........am i right?

2) suppose if no Formatters added in App_Start/WebApiConfig.cs file then we need to send some inform from web api client just to say i need response in json format. see the below code.

HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:38762/api/customer/AddCustome");
client.DefaultRequestHeaders
  .Accept
  .Add(new MediaTypeWithQualityHeaderValue("application/json"));

am i right ?

it means both the code is doing same thing.........am i right ?

web api action which has two different type of parameter

$
0
0

I have one web api action which take two parameter one is string type and another one is customer type object. I like to know how could i call that post type action where i can pass one string value and one customer json. Please give me code with httpclient
class which will call that action with postasync and pass customer id as string value for one parameter and we need to pass customer object json as second param value. Looking for example code.

how many way we can enable cors

$
0
0
How to enable cors for full project and how to enable it for few action?
Viewing all 4850 articles
Browse latest View live


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